Merge pull request #63 from Kitzanos/develop

Sync master with develop branch(25/10/2024)
Hub Management 
Review Properties
This commit is contained in:
rbonazzo-KZ
2024-10-25 09:13:04 +02:00
committed by GitHub
120 changed files with 3526 additions and 860 deletions

View File

@@ -212,6 +212,13 @@
<version>8.0.5</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<repositories>
<repository>

View File

@@ -29,6 +29,7 @@ import org.opensaml.xmlsec.signature.support.SignatureConstants;
import org.opensaml.xmlsec.signature.support.Signer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -41,6 +42,13 @@ import org.springframework.security.saml2.provider.service.web.DefaultRelyingPar
import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver;
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
import org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
@Configuration
public class SamlConfig {
@@ -56,6 +64,9 @@ public class SamlConfig {
@Value("${active.profile.folder}")
String activeProfileFolder;
@Autowired
private SamlResponseRepository samlResponseRepository;
@Bean
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
@@ -129,15 +140,26 @@ public Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingP
OpenSaml4AuthenticationRequestResolver authenticationRequestResolver = new OpenSaml4AuthenticationRequestResolver(registrationResolver);
authenticationRequestResolver.setAuthnRequestCustomizer((context) -> {
// Set the required attributes
AuthnRequest authnRequest = context.getAuthnRequest();
authnRequest.setID("_" + UUID.randomUUID().toString()); // Add a unique ID
authnRequest.setVersion(SAMLVersion.VERSION_20); // Ensure version is 2.0
authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI); // HTTP-POST
// 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());
SamlResponseEntity samlResponse = new SamlResponseEntity();
samlResponse.setHubUuid(hubUuid);
samlResponse.setInResponseTo(inResponseTo);
samlResponse.setStatus(SamlResponseStatusEnum.INITIATED.getValue());
samlResponseRepository.save(samlResponse);
// Log the SAML AuthnRequest after setting context
String samlRequest = SamlRequestLogger.convertSAMLObjectToString(authnRequest);
logger.info("SAML AuthnRequest after setting context: " + samlRequest);
@@ -146,6 +168,7 @@ public Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingP
return authenticationRequestResolver;
}
private RequestedAuthnContext buildRequestedAuthnContext() {
AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(

View File

@@ -1,9 +1,13 @@
package net.gepafin.tendermanagement.config;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
@@ -11,6 +15,12 @@ import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@Component
public class SamlFailureHandler implements AuthenticationFailureHandler {
@@ -20,16 +30,40 @@ public class SamlFailureHandler implements AuthenticationFailureHandler {
@Value("${fe.base.url}")
private String feBaseUrl;
@Autowired
private SamlResponseRepository samlResponseRepository;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
try {
logger.error("SAML login failed: " + exception.getMessage());
String inResponseTo = extractInResponseTo(feBaseUrl);
if (Boolean.FALSE.equals(StringUtils.isEmpty(inResponseTo))) {
SamlResponseEntity samlResponseLogEntity = samlResponseRepository
.findByInResponseToAndStatus(inResponseTo, SamlResponseStatusEnum.INITIATED.getValue())
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.INVALID_REQUEST)));
samlResponseLogEntity.setStatus(SamlResponseStatusEnum.FAILED.getValue());
samlResponseRepository.save(samlResponseLogEntity);
}
response.sendRedirect(feBaseUrl + "/login");
} catch (Exception e) {
logger.error("Error processing SAML failure handler", e);
}
}
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;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -13,16 +18,21 @@ import org.springframework.security.saml2.provider.service.authentication.Saml2A
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -41,6 +51,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
@Value("${fe.base.url}")
private String feBaseUrl;
@Autowired
private HubService hubService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
@@ -53,20 +66,51 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
String token = Utils.generateSecureToken();
logger.info("SAML User Attributes: " + userAttributes);
SamlResponseEntity samlResponseLogEntity = new SamlResponseEntity();
samlResponseLogEntity.setAuthenticationObject(authentication.toString());
// Extracting raw SAML response
String samlResponse = samlAuth.getSaml2Response();
logger.info("Raw SAML Response: " + samlResponse);
// If samlResponse is already in XML format, do not Base64 decode it
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(samlResponse.getBytes())); // Remove the Base64 decoding
// Extracting ID, InResponseTo, and IssueInstant from the Response element
Element responseElement = (Element) document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "Response").item(0);
String responseId = responseElement.getAttribute("ID");
String inResponseTo = responseElement.getAttribute("InResponseTo");
String issueInstant = responseElement.getAttribute("IssueInstant");
logger.info("SAML Response ID: " + responseId);
logger.info("InResponseTo: " + inResponseTo);
logger.info("IssueInstant: " + issueInstant);
SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository
.findByInResponseToAndStatus(inResponseTo, SamlResponseStatusEnum.INITIATED.getValue())
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.INVALID_REQUEST)));
ObjectMapper objectMapper = new ObjectMapper();
String userAttributesJson = objectMapper.writeValueAsString(userAttributes);
samlResponseLogEntity.setAuthenticationObject(userAttributesJson);
samlResponseLogEntity.setToken(token);
samlResponseLogEntity.setStatus(SamlResponseStatusEnum.SUCCESS.getValue());
samlResponseLogEntity.setInResponseTo(inResponseTo);
samlResponseLogEntity.setSamlId(responseId);
samlResponseLogEntity.setIssueInstant(issueInstant);
samlResponseLogRepository.save(samlResponseLogEntity);
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
String redirectUrl = feBaseUrl;
if (Boolean.FALSE.equals(StringUtils.isEmpty(hub.getDomainName()))) {
redirectUrl = hub.getDomainName();
}
logger.info("SAML login successful for user: " + principal.getName());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf).orElse(null);
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscaleAndHubId(cf, hub.getId()).orElse(null);
if (userEntity == null) {
redirectUrl += "/registration?temp_token=" + token;
} else {
@@ -79,9 +123,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
}
}
public void validateToken(String token, String codiceFiscale) {
public void validateToken(String token, String codiceFiscale, String hubUuid) {
SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository.findByToken(token);
if (samlResponseLogEntity == null) {
if (samlResponseLogEntity == null || Boolean.FALSE.equals(hubUuid.equals(samlResponseLogEntity.getHubUuid()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
@@ -92,7 +136,6 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
samlResponseLogRepository.delete(samlResponseLogEntity);
}
}

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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.saml2.provider.service.web.Saml2WebSsoAuthenticationRequestFilter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
@@ -106,6 +107,8 @@ public class SecurityConfig {
.requestMatchers("/saml2/**").permitAll() // SAML login initiation
.requestMatchers("/swagger-ui/**").permitAll() // Swagger docs
.requestMatchers("/v1/api-docs/**").permitAll() // API docs
.requestMatchers("/v1/user/reset-password/initiate").permitAll()
.requestMatchers("/v1/user/reset-password").permitAll()
.anyRequest().authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
.exceptionHandling(exceptionHandling -> exceptionHandling
@@ -116,15 +119,11 @@ public class SecurityConfig {
)
.addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
// Add SAML2 login configuration (for BENEFICIARI)
/*
* .saml2Login(saml -> saml.loginPage("/saml/login") // Entry point for SAML
* login .defaultSuccessUrl("/") // Redirect after successful SAML login );
*/
.saml2Login(saml -> saml.defaultSuccessUrl("/").successHandler(samlSuccessHandler)
.addFilterBefore(new SamlRequestFilter(), Saml2WebSsoAuthenticationRequestFilter.class) // Add the custom SAML filter
.saml2Login(saml -> saml.defaultSuccessUrl("/")
.successHandler(samlSuccessHandler)
.failureHandler(samlFailureHandler));
return http.build();
}

View File

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

View File

@@ -225,9 +225,31 @@ public class GepafinConstant {
public static final String DD_MM_YYYY = "dd/MM/yyyy";
public static final String DASHBOARD_WIDGET_FETCHED_SUCCESSFULLY="dashboard.widget.fetched.successfully";
public static final Integer DEFAULT_PAGE_LIMIT = 1000;
public static final Integer DEFAULT_PAGE = 1;
public static final String ATTEMPT_DATE = "attemptDate";
public static final String LOGIN_ATTEMPTED_CREATED_SUCCESSFULLY="login_attempt_successfully_created";
public static final String GET_LOGIN_ATTEMPT_MSG="get_login_attempt_se_msg";
public static final String CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT = "application.in.submit.status.cannot.delete.company";
public static final String GET_USERS_SUCCESS_MSG = "get.users.success.msg";
public static final String CANNOT_CREATE_BENEFICIARY_USER="cannot.create.beneficiary.user";
public static final String APPLICATION_ASSIGNED= "application.assigned.success.msg";
public static final String APPLICATION_ALREADY_ASSIGNED = "application.already.assigned.msg";
public static final String ASSIGNED_APPLICATION_NOT_FOUND_MSG="aasigned.application.not.found";
public static final String DELETE_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.deleted.success";
public static final String GET_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.get.success";
public static final String ASSIGNED_APPLICATION_UPDATE_SUCCESSFULLY_MSG = "assigned.application.update.successfully";
public static final String HUB_CREATE_SUCCESS = "hub_create_success";
public static final String HUB_UPDATE_SUCCESS = "hub_update_success";
public static final String HUB_GET_SUCCESS = "hub_get_success";
public static final String HUB_GET_ALL_SUCCESS = "hub_get_all_success";
public static final String HUB_DELETE_SUCCESS = "hub_delete_success";
public static final String HUB_NOT_FOUND = "hub_not_found";
public static final String EVALUATIONCRITERIA_INVALID = "evaluationCriteria.invalid";
public static final String APPLICATION_NOT_IN_DRAFT_STATUS="application.not.in.draft.status";
public static final String GET_ERROR_S3 = "get.error.s3";
public static final String INVALID_APPLICATION_STATUS = "invalid.application.status";
}

View File

@@ -20,6 +20,7 @@ import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.DocumentService;
import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.MailUtil;
@@ -120,14 +121,21 @@ public class ApplicationDao {
@Value("${aws.s3.url.folder.signed.document}")
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);
// callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId);
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED));
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if(Boolean.FALSE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.DRAFT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
}
formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity);
ApplicationFormEntity applicationFormEntity = getApplicationFormOrCreate(formEntity, applicationEntity);
@@ -167,6 +175,7 @@ public class ApplicationDao {
entity.setUserId(user.getId());
entity.setCompany(companyEntity);
entity.setCall(call);
entity.setHubId(call.getHub().getId());
entity.setIsDeleted(false);
entity.setStatus(ApplicationStatusTypeEnum.DRAFT.getValue());
return entity;
@@ -229,10 +238,11 @@ public class ApplicationDao {
return applicationFormFieldResponseBeans;
}
public void deleteById(Long id) {
public void deleteById(HttpServletRequest request, Long id) {
log.info("Deleting application with ID: {}", id);
ApplicationEntity applicationEntity= validateApplication(id);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
applicationEntity.setIsDeleted(true);
applicationEntity=saveApplicationEntity(applicationEntity);
log.info("Application deleted with ID: {}", id);
@@ -274,11 +284,11 @@ public class ApplicationDao {
// return applicationResponses;
// }
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId) {
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId,String status) {
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
Specification<ApplicationEntity> spec = search(userEntity.getId(), callId, companyId);
Specification<ApplicationEntity> spec = search(userEntity, callId, companyId,status);
List<ApplicationEntity> applicationEntities = applicationRepository.findAll(spec);
@@ -288,12 +298,12 @@ public class ApplicationDao {
}
private Specification<ApplicationEntity> search(Long userId, Long callId, Long companyId) {
private Specification<ApplicationEntity> search(UserEntity userEntity, Long callId, Long companyId,String status) {
return (root, query, builder) -> {
Boolean isBeneficiary = validator.checkIsBeneficiary();
Predicate predicate = builder.isFalse(root.get("isDeleted"));
if (isBeneficiary) {
predicate = builder.and(predicate, builder.equal(root.get("userId"), userId));
predicate = builder.and(predicate, builder.equal(root.get("userId"), userEntity.getId()));
}
if (callId != null) {
predicate = builder.and(predicate, builder.equal(root.get("call").get("id"), callId));
@@ -301,6 +311,10 @@ public class ApplicationDao {
if (companyId != null) {
predicate = builder.and(predicate, builder.equal(root.get("company").get("id"), companyId));
}
if (status != null) {
predicate = builder.and(predicate, builder.equal(root.get("status"), status));
}
predicate = builder.and(predicate, builder.equal(root.get("hubId"), userEntity.getHub().getId()));
return predicate;
};
}
@@ -467,9 +481,10 @@ public class ApplicationDao {
return applicationEntity;
}
public ApplicationGetResponseBean getApplicationByFormId( Long applicationId, Long formId, UserEntity userEntity) {
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId, Long formId) {
List<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
List<FormEntity> formEntities = new ArrayList<>();
UserEntity userEntity = validator.validateUser(request);
boolean isBeneficiary = isBeneficiary(userEntity);
ApplicationEntity applicationEntity = isBeneficiary
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
@@ -574,8 +589,10 @@ public class ApplicationDao {
}
}
public ApplicationResponse updateApplicationStatus(UserEntity userEntity, Long applicationId, ApplicationStatusTypeEnum status) {
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
}
@@ -583,41 +600,32 @@ public class ApplicationDao {
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(status.getValue()))){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_IN_PREVIOUS_STATUS));
}
if (status.equals(ApplicationStatusTypeEnum.SUBMIT)) {
callService.validatePublishedCall(applicationEntity.getCall().getId());
// CallEntity callEntity = applicationEntity.getCall();
// Long initialFormId = callEntity.getInitialForm();
// Long finalFormId = callEntity.getFinalForm();
//// if (initialFormId == null || finalFormId == null) {
//// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
//// }
// ApplicationFormEntity initialApplicationForm = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), initialFormId);
// ApplicationFormEntity finalApplicationForm = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), finalFormId);
// if (initialApplicationForm == null || finalApplicationForm == null) {
// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
// }
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalSteps=flowFormDao.calculateTotalSteps(flowEdgesList);
Integer completedSteps=flowFormDao.getCompletedSteps(applicationEntity);
if (totalSteps.intValue() != completedSteps) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
Integer maxProtocolNumber=protocolRepository.findMaxProtocolNumber();
Integer protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 1;
ProtocolEntity protocolEntity=createProtocolEntity(applicationEntity,protocolNumber);
if (status.equals(ApplicationStatusTypeEnum.SUBMIT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
callService.validatePublishedCall(applicationEntity.getCall().getId(), userEntity.getHub().getId());
Long protocolNumber = getProtocolNumber(userEntity.getHub());
ProtocolEntity protocolEntity = createProtocolEntity(applicationEntity,protocolNumber, userEntity.getHub().getId());
applicationEntity.setProtocol(protocolEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
applicationEntity = saveApplicationEntity(applicationEntity);
sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
} else {
applicationEntity.setStatus(status.getValue());
}
applicationEntity = saveApplicationEntity(applicationEntity);
}
return getApplicationResponse(applicationEntity);
}
private Long getProtocolNumber(HubEntity hubEntity) {
Long maxProtocolNumber = protocolRepository.findMaxProtocolNumberAndHubId(hubEntity.getId());
Long startNumber = 10000001L;
if(Boolean.FALSE.equals(defaultHubUuid.equals(hubEntity.getUniqueUuid()))) {
startNumber = 20000001L;
}
return (maxProtocolNumber != null) ? maxProtocolNumber + 1 : startNumber;
}
public Integer calculateProgress(Long totalSteps, Long completedSteps) {
if (FieldValidator.isNullOrZero(totalSteps)) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.TOTAL_STEPS_NOT_BE_ZERO));
@@ -691,14 +699,15 @@ public class ApplicationDao {
}
}
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Integer protocolNumber){
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Long protocolNumber, Long hubId){
ProtocolEntity protocolEntity=new ProtocolEntity();
protocolEntity.setCall(applicationEntity.getCall().getId());
LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
protocolEntity.setYear(utcDateTime.getYear());
protocolEntity.setProtocolNumber(Long.valueOf(protocolNumber));
protocolEntity.setProtocolNumber(protocolNumber);
protocolEntity.setTime(LocalTime.now());
protocolEntity.setApplicationId(applicationEntity.getId());
protocolEntity.setHubId(hubId);
protocolRepository.save(protocolEntity);
return protocolEntity;
}
@@ -763,7 +772,9 @@ public class ApplicationDao {
mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
if(validator.isProductionProfileActivated()) {
mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
}
}
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,
@@ -774,8 +785,9 @@ public class ApplicationDao {
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if (applicationSignedDocument != null) {
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_ASSIGNED));
// applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
// applicationSignedDocumentRepository.save(applicationSignedDocument);
}
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = amazonS3Service.uploadFileOnAmazonS3(signedDocumentS3Folder,
file);
@@ -785,6 +797,8 @@ public class ApplicationDao {
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
applicationEntity.setStatus(ApplicationStatusTypeEnum.READY.getValue());
applicationRepository.save(applicationEntity);
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
@@ -841,4 +855,24 @@ public class ApplicationDao {
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.DRAFT.getValue().equals(applicationEntity.getStatus()))) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
}
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalSteps=flowFormDao.calculateTotalSteps(flowEdgesList);
Integer completedSteps=flowFormDao.getCompletedSteps(applicationEntity);
if (totalSteps.intValue() != completedSteps) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
applicationEntity.setStatus(ApplicationStatusTypeEnum.AWAITING.getValue());
applicationEntity = saveApplicationEntity(applicationEntity);
return getApplicationResponse(applicationEntity);
}
}

View File

@@ -0,0 +1,207 @@
package net.gepafin.tendermanagement.dao;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
import net.gepafin.tendermanagement.service.ApplicationService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.log;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class AssignedApplicationsDao {
@Autowired
private ApplicationService applicationService;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private AssignedApplicationsRepository assignedApplicationsRepository;
@Autowired
private UserService userService;
@Autowired
private Validator validator;
public AssignedApplicationsResponse createAssignedApplications(Long applicationId, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest){
log.info("Assigning application to pre-Instructor with details: {}", applicationId,userId);
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
if(assignedApplications!=null){
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_ASSIGNED));
}
ApplicationEntity application = applicationService.validateApplication(applicationId);
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.SUBMIT.getValue().equals(application.getStatus()))) {
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.INVALID_APPLICATION_STATUS)
);
}
application.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
applicationRepository.save(application);
UserEntity user = userService.validateUser(userId);
AssignedApplicationsEntity assignment = createAssignmentEntity(application, user.getId(), assignedByUser, assignedApplicationsRequest);
AssignedApplicationsResponse assignApplicationToInstructorResponse = convertEntityToResponse(assignment);
log.info("Application assigned succesfully {}", assignApplicationToInstructorResponse);
return assignApplicationToInstructorResponse;
}
public AssignedApplicationsEntity createAssignmentEntity(ApplicationEntity application, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest){
AssignedApplicationsEntity assignApplication= new AssignedApplicationsEntity();
assignApplication.setApplication(application);
assignApplication.setAssignedBy(assignedByUser.getId());
assignApplication.setUserId(userId);
assignApplication.setStatus(AssignedApplicationEnum.ASSIGNED.getValue());
if(assignedApplicationsRequest.getStatus() != null) {
assignApplication.setStatus(assignedApplicationsRequest.getStatus().getValue());
}
assignApplication.setNote(assignedApplicationsRequest.getNote());
assignApplication.setIsDeleted(false);
assignApplication.setAssignedAt(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
AssignedApplicationsEntity assignedApplicationsEntity = saveAssignedApplication(assignApplication);
return assignedApplicationsEntity;
}
public AssignedApplicationsEntity saveAssignedApplication(AssignedApplicationsEntity assignedApplicationsEntity){
AssignedApplicationsEntity assignedApplication= assignedApplicationsRepository.save(assignedApplicationsEntity);
return assignedApplication;
}
public AssignedApplicationsResponse convertEntityToResponse(AssignedApplicationsEntity assignedApplications){
AssignedApplicationsResponse assignedApplicationsResponse = new AssignedApplicationsResponse();
assignedApplicationsResponse.setId(assignedApplications.getId());
assignedApplicationsResponse.setApplicationId(assignedApplications.getApplication().getId());
ApplicationEntity application = applicationService.validateApplication(assignedApplications.getApplication().getId());
String callName = application.getCall() != null ? application.getCall().getName() : "";
LocalDateTime callEndDate = application.getCall().getEndDate();
LocalDateTime callStartDate = application.getCall().getStartDate();
Long protocolNumber = (application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null)
? application.getProtocol().getProtocolNumber()
: 0;
LocalDateTime submissionDate = application.getSubmissionDate();
UserEntity userEntity = userService.validateUser(application.getUserId());
String firstName = userEntity.getBeneficiary() != null ? userEntity.getBeneficiary().getFirstName() : null;
String lastName = userEntity.getBeneficiary() != null ? userEntity.getBeneficiary().getLastName() : null;
String beneficiaryName = (firstName != null && !firstName.isBlank() ? firstName : "") +
(lastName != null && !lastName.isBlank() ? " " + lastName : "");
beneficiaryName = beneficiaryName.isBlank() ? "" : beneficiaryName;
assignedApplicationsResponse.setAssignedBy(assignedApplications.getAssignedBy());
assignedApplicationsResponse.setUserId(assignedApplications.getUserId());
assignedApplicationsResponse.setCreatedDate(assignedApplications.getCreatedDate());
assignedApplicationsResponse.setUpdatedDate(assignedApplications.getUpdatedDate());
assignedApplicationsResponse.setNote(assignedApplications.getNote());
assignedApplicationsResponse.setStatus(AssignedApplicationEnum.valueOf(assignedApplications.getStatus()));
assignedApplicationsResponse.setAssignedAt(assignedApplications.getAssignedAt());
assignedApplicationsResponse.setProtocolNumber(protocolNumber);
assignedApplicationsResponse.setCallName(callName);
assignedApplicationsResponse.setBeneficiaryName(beneficiaryName);
assignedApplicationsResponse.setSubmissionDate(submissionDate);
assignedApplicationsResponse.setCallEndDate(callEndDate);
assignedApplicationsResponse.setCallStartDate(callStartDate);
return assignedApplicationsResponse;
}
public AssignedApplicationsEntity validateAssignedApplication(Long id){
AssignedApplicationsEntity assignedApplication = assignedApplicationsRepository.findByIdAndIsDeletedFalse(id).orElseThrow(()->
new ResourceNotFoundException(Status.NOT_FOUND,Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_MSG)));
return assignedApplication;
}
public void deleteById(HttpServletRequest request, Long id) {
log.info("Deleting assigned application with ID: {}", id);
AssignedApplicationsEntity assignedApplicationsEntity= validateAssignedApplication(id);
validator.validatePreInstructor(request, assignedApplicationsEntity.getUserId());
assignedApplicationsEntity.setIsDeleted(true);
assignedApplicationsEntity= saveAssignedApplication(assignedApplicationsEntity);
log.info("Assigned Application deleted with ID: {}", id);
}
public List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId) {
UserEntity user = validator.validateUser(request);
if(validator.checkIsPreInstructor() && userId == null) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.USER_ID_NOT_NULL_MSG));
}
if(userId != null) {
validator.validatePreInstructor(request, userId);
}
Specification<AssignedApplicationsEntity> spec = search(user.getHub().getId() ,userId);
List<AssignedApplicationsEntity> assignedApplicationsEntityList = assignedApplicationsRepository.findAll(spec);
return assignedApplicationsEntityList.stream()
.map(entity -> convertEntityToResponse(entity))
.collect(Collectors.toList());
}
private Specification<AssignedApplicationsEntity> search(Long hubId, Long userId) {
return (root, query, builder) -> {
Predicate predicate = builder.isFalse(root.get("isDeleted"));
if (userId != null) {
predicate = builder.and(predicate, builder.equal(root.get("userId"), userId));
}
predicate = builder.and(predicate, builder.equal(root.get("application").get("hubId"), hubId));
return predicate;
};
}
public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request,
Long id, AssignedApplicationsRequest updateRequest) {
UserEntity updatedByUser = validator.validateUser(request);
log.info("Updating assigned application with ID: {}", id);
AssignedApplicationsEntity existingAssignment = validateAssignedApplication(id);
validator.validatePreInstructor(request, existingAssignment.getUserId());
setIfUpdated(existingAssignment::getNote, existingAssignment::setNote, updateRequest.getNote());
setIfUpdated(existingAssignment::getStatus, existingAssignment::setStatus, updateRequest.getStatus().name());
setIfUpdated(existingAssignment::getAssignedBy, existingAssignment::setAssignedBy, updatedByUser.getId());
existingAssignment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
AssignedApplicationsEntity updatedAssignment = saveAssignedApplication(existingAssignment);
AssignedApplicationsResponse response = convertEntityToResponse(updatedAssignment);
log.info("Assigned application updated successfully: {}", response);
return response;
}
public AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id) {
log.info("Fetching assigned application with ID: {}", id);
AssignedApplicationsEntity assignedApplication = validateAssignedApplication(id);
validator.validatePreInstructor(request, assignedApplication.getUserId());
AssignedApplicationsResponse response = convertEntityToResponse(assignedApplication);
log.info("Assigned application fetched successfully: {}", response);
return response;
}
}

View File

@@ -5,13 +5,11 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryPreferredCallEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.BeneficiaryCallStatus;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.BeneficiaryPreferredCallReq;
import net.gepafin.tendermanagement.model.response.BeneficiaryPreferredCallResponseBean;
import net.gepafin.tendermanagement.repositories.BeneficiaryPreferredCallRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.slf4j.Logger;
@@ -19,10 +17,11 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class BeneficiaryPreferredCallDao {
@@ -31,11 +30,14 @@ public class BeneficiaryPreferredCallDao {
@Autowired
private BeneficiaryPreferredCallRepository beneficiaryPreferredCallRepository;
@Autowired
private UserService userService;
public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(BeneficiaryPreferredCallReq request,UserEntity user) {
@Autowired
private Validator validator;
public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(HttpServletRequest httpServletRequest, BeneficiaryPreferredCallReq request,UserEntity user) {
log.info("Creating new beneficiary preferred call with details: {}", request);
validator.validateUserWithCompany(httpServletRequest, request.getCompanyId());
BeneficiaryPreferredCallEntity entity = convertRequestToEntity(request,user);
entity = beneficiaryPreferredCallRepository.save(entity);
log.info("Beneficiary preferred call created with ID: {}", entity.getId());
@@ -44,9 +46,8 @@ public class BeneficiaryPreferredCallDao {
private BeneficiaryPreferredCallEntity convertRequestToEntity(BeneficiaryPreferredCallReq request,UserEntity userEntity) {
BeneficiaryPreferredCallEntity entity = new BeneficiaryPreferredCallEntity();
UserEntity user= userService.validateUser(userEntity.getId());
if (user.getBeneficiary()!=null) {
entity.setBeneficiaryId(user.getBeneficiary().getId());
if (userEntity.getBeneficiary()!=null) {
entity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
entity.setStatus(BeneficiaryCallStatus.ENABLED.getValue());
entity.setCallId(request.getCallId());
@@ -55,9 +56,10 @@ public class BeneficiaryPreferredCallDao {
return entity;
}
public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(Long id) {
public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(HttpServletRequest request, Long id) {
log.info("Fetching beneficiary preferred call with ID: {}", id);
BeneficiaryPreferredCallEntity entity = validateBeneficiaryPreferredCall(id);
validator.validateUserId(request, entity.getUserId());
log.info("Beneficiary preferred call found: {}", entity);
return convertEntityToResponse(entity);
}
@@ -74,20 +76,18 @@ public class BeneficiaryPreferredCallDao {
// return convertEntityToResponse(existingEntity);
// }
private boolean isUserABeneficiary(Long userId) {
UserEntity user=userService.validateUser(userId);
return RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(user.getRoleEntity().getRoleType());
}
public void deleteBeneficiaryPreferredCallById(Long id) {
public void deleteBeneficiaryPreferredCallById(HttpServletRequest request, Long id) {
log.info("Deleting beneficiary preferred call with ID: {}", id);
validateBeneficiaryPreferredCall(id);
BeneficiaryPreferredCallEntity entity = validateBeneficiaryPreferredCall(id);
validator.validateUserId(request, entity.getUserId());
beneficiaryPreferredCallRepository.deleteById(id);
log.info("Beneficiary preferred call deleted with ID: {}", id);
}
public List<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls() {
public List<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls(HttpServletRequest request) {
UserEntity userEntity = validator.validateUser(request);
log.info("Fetching all beneficiary preferred calls");
List<BeneficiaryPreferredCallResponseBean> calls = beneficiaryPreferredCallRepository.findAll()
List<BeneficiaryPreferredCallResponseBean> calls = beneficiaryPreferredCallRepository.findByUserId(userEntity.getId())
.stream()
.map(this::convertEntityToResponse)
.collect(Collectors.toList());

View File

@@ -1,6 +1,5 @@
package net.gepafin.tendermanagement.dao;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -23,10 +22,6 @@ import net.gepafin.tendermanagement.util.Utils;
import org.h2.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -34,6 +29,7 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CallTargetAudienceChecklistEntity;
import net.gepafin.tendermanagement.entities.CriteriaFormFieldEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity;
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
import net.gepafin.tendermanagement.entities.FaqEntity;
@@ -52,6 +48,7 @@ import net.gepafin.tendermanagement.model.request.LookUpDataReq;
import net.gepafin.tendermanagement.model.request.UpdateCallRequestStep1;
import net.gepafin.tendermanagement.repositories.CallRepository;
import net.gepafin.tendermanagement.repositories.CallTargetAudienceChecklistRepository;
import net.gepafin.tendermanagement.repositories.CriteriaFormFieldRepository;
import net.gepafin.tendermanagement.repositories.DocumentRepository;
import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository;
import net.gepafin.tendermanagement.repositories.FaqRepository;
@@ -89,23 +86,26 @@ public class CallDao {
private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository;
@Autowired
private UserService userService;
private FaqService faqService;
@Autowired
private FaqService faqService;
@Autowired
private FlowDao flowDao;
@Autowired
private FormDao formDao;
@Value("${aws.s3.url.folder}")
private String s3Folder;
@Autowired
private AmazonS3Service amazonS3Service;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) {
UserEntity userEntity = userService.validateUser(userId);
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
CallEntity callEntity = convertToCallEntity(createCallRequest);
CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ);
@@ -148,7 +148,7 @@ public class CallDao {
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest) {
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
CallEntity callEntity = new CallEntity();
// validateCallEntity(createCallRequest);
RegionEntity region = regionRepository.findById(createCallRequest.getRegionId())
@@ -184,6 +184,7 @@ public class CallDao {
callEntity.setPhoneNumber(createCallRequest.getPhoneNumber());
callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime()));
callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime()));
callEntity.setHub(userEntity.getHub());
callEntity = callRepository.save(callEntity);
return callEntity;
}
@@ -209,6 +210,12 @@ public class CallDao {
private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) {
evaluationCriteriaEntity.setIsDeleted(true);
evaluationCriteriaRepository.save(evaluationCriteriaEntity);
List<CriteriaFormFieldEntity> list = criteriaFormFieldRepository
.findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaEntity.getId())
.stream()
.peek(data -> data.setIsDeleted(Boolean.TRUE))
.toList();
criteriaFormFieldRepository.saveAll(list);
}
private EvaluationCriteriaEntity convertToEvaluationCriteriaEntity(EvaluationCriteriaReq criteriaReq,
@@ -257,6 +264,7 @@ public class CallDao {
private void softDeleteDocument(DocumentEntity documentEntity) {
documentEntity.setIsDeleted(true);
documentRepository.save(documentEntity);
}
private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) {
@@ -424,13 +432,11 @@ public class CallDao {
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)));
}
public CallResponse getCallById(Long callId) {
CallEntity callEntity = validateCall(callId);
public CallResponse getCallById(CallEntity callEntity) {
return getCallResponseBean(callEntity);
}
public CallResponse createCallStep2(Long callId, CreateCallRequestStep2 createCallRequest, Long userId) {
CallEntity callEntity = validateCall(callId);
public CallResponse createCallStep2(CallEntity callEntity, CreateCallRequestStep2 createCallRequest, UserEntity user) {
validateUpdate(callEntity);
setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold());
callRepository.save(callEntity);
@@ -490,8 +496,7 @@ public class CallDao {
}
}
public CallResponse updateCallStep1(Long callId, UpdateCallRequestStep1 updateCallRequest, Long userId) {
CallEntity callEntity = validateCall(callId);
public CallResponse updateCallStep1(CallEntity callEntity, UpdateCallRequestStep1 updateCallRequest, UserEntity userEntity) {
if(Boolean.TRUE.equals(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue()))) {
try {
Utils.retainOnlySpecificFields(updateCallRequest, Collections.singletonList("faq"));
@@ -499,7 +504,6 @@ public class CallDao {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FAILED_RETAIN_FIELD));
}
}
UserEntity userEntity = userService.validateUser(userId);
isValidDateRange(updateCallRequest, callEntity);
setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName());
setIfUpdated(callEntity::getDescriptionShort, callEntity::setDescriptionShort,
@@ -553,9 +557,9 @@ public class CallDao {
}
List<CallTargetAudienceChecklistEntity> existingChecklist = callTargetAudienceChecklistRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), type.getValue());
List<Long> incomingIds = lookupDataReqList.stream().map(LookUpDataReq::getLookUpDataId)
List<Long> incomingIds = lookupDataReqList.stream().map(LookUpDataReq::getId)
.filter(id -> id != null && id > 0).collect(Collectors.toList());
existingChecklist.stream().filter(checklist -> !incomingIds.contains(checklist.getLookupData().getId()))
existingChecklist.stream().filter(checklist -> !incomingIds.contains(checklist.getId()))
.forEach(this::softDeleteCallTargetAudienceChecklist);
lookupDataReqList
.forEach(lookUpDataReq -> createOrUpdateCallTargetAudienceChecklist(lookUpDataReq, callEntity, type));
@@ -650,7 +654,7 @@ public class CallDao {
if (Boolean.FALSE.equals(ROLE_SUPER_ADMIN.getValue().equals(type))) {
callStatusList = List.of(CallStatusEnum.PUBLISH.getValue());
}
List<CallEntity> calls = callRepository.findByStatusIn(callStatusList);
List<CallEntity> calls = callRepository.findByStatusInAndHubId(callStatusList, user.getHub().getId());
return calls.stream()
.map(this::convertToCallDetailsResponseBean)
.collect(Collectors.toList());
@@ -660,7 +664,7 @@ public class CallDao {
validateUpdate(callEntity);
CallResponse callResponseBean = getCallResponseBean(callEntity);
FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId());
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity.getId());
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity);
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean);
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
callRepository.save(callEntity);
@@ -668,16 +672,15 @@ public class CallDao {
callResponseBean.setStatus(CallStatusEnum.valueOf(callEntity.getStatus()));
return callResponseBean;
}
public CallEntity getCallEntityById(Long id){
CallEntity callEntity=callRepository.findByIdAndStatusNotIn(id,List.of(CallStatusEnum.PUBLISH.getValue()));
if(callEntity==null){
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
}
return callEntity;
}
// public CallEntity getCallEntityById(Long id){
// CallEntity callEntity=callRepository.findByIdAndStatusNotInAndHubId(id, List.of(CallStatusEnum.PUBLISH.getValue()));
// if(callEntity==null){
// throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
// }
// return callEntity;
// }
public CallResponse updateCallStatus(Long callId, CallStatusEnum statusReq) {
CallEntity callEntity = validateCall(callId);
public CallResponse updateCallStatus(CallEntity callEntity, CallStatusEnum statusReq) {
CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus());
validateStatusChange(currentStatus, statusReq);
callEntity.setStatus(statusReq.getValue());
@@ -715,9 +718,9 @@ public class CallDao {
}
}
public CallEntity validatePublishedCall(Long callId) {
public CallEntity validatePublishedCall(Long callId, Long hubId) {
CallEntity callEntity= callRepository
.findByIdAndStatus(callId, CallStatusEnum.PUBLISH.getValue());
.findByIdAndStatusAndHubId(callId, CallStatusEnum.PUBLISH.getValue(), hubId);
if(callEntity==null){
throw new ResourceNotFoundException(
Status.NOT_FOUND,

View File

@@ -2,25 +2,23 @@ package net.gepafin.tendermanagement.dao;
import java.util.List;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.repositories.FaqRepository;
import net.gepafin.tendermanagement.web.rest.api.errors.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.repositories.CompanyRepository;
import net.gepafin.tendermanagement.repositories.UserWithCompanyRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@@ -35,13 +33,17 @@ public class CompanyDao {
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private FaqRepository faqRepository;
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
CompanyEntity existingCompany = companyRepository.findByVatNumber(companyRequest.getVatNumber());
CompanyEntity existingCompany = companyRepository.findByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId());
UserWithCompanyEntity userWithCompanyEntity = null;
if (existingCompany != null) {
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyId(userEntity.getId(), existingCompany.getId())
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), existingCompany.getId())
.orElse(null);
if (existingRelation == null) {
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant());
@@ -51,8 +53,8 @@ public class CompanyDao {
}
return convertCompanyEntityToCompanyResponse(existingCompany, userWithCompanyEntity);
} else {
validateCompany(companyRequest);
CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(companyRequest);
validateCompany(userEntity, companyRequest);
CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(userEntity, companyRequest);
companyRepository.save(companyEntity);
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
@@ -60,7 +62,7 @@ public class CompanyDao {
}
private void validateCompany(CompanyRequest companyRequest) {
private void validateCompany(UserEntity userEntity, CompanyRequest companyRequest) {
if (Boolean.FALSE.equals(StringUtils.isEmpty(companyRequest.getEmail()))
&& Boolean.FALSE.equals(Utils.isValidEmail(companyRequest.getEmail()))) {
@@ -71,7 +73,7 @@ public class CompanyDao {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_MANDATORY));
}
if (companyRepository.existsByVatNumber(companyRequest.getVatNumber())) {
if (companyRepository.existsByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
}
@@ -82,13 +84,14 @@ public class CompanyDao {
if (userEntity.getBeneficiary() != null) {
userWithCompanyEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
userWithCompanyEntity.setIsDeleted(Boolean.FALSE);
userWithCompanyEntity.setCompanyId(companyEntity.getId());
userWithCompanyEntity.setUserId(userEntity.getId());
userWithCompanyEntity.setIsLegalRepresentant(isLegalRepresentant);
return userWithCompanyRepository.save(userWithCompanyEntity);
}
private CompanyEntity convertCompanyRequestToCompanyEntity(CompanyRequest request) {
private CompanyEntity convertCompanyRequestToCompanyEntity(UserEntity userEntity, CompanyRequest request) {
CompanyEntity entity = new CompanyEntity();
entity.setCompanyName(request.getCompanyName());
entity.setVatNumber(request.getVatNumber());
@@ -105,6 +108,7 @@ public class CompanyDao {
entity.setAnnualRevenue(request.getAnnualRevenue());
entity.setContactName(request.getContactName());
entity.setContactEmail(request.getContactEmail());
entity.setHub(userEntity.getHub());
return entity;
}
@@ -177,27 +181,49 @@ public class CompanyDao {
public void deleteCompany(UserEntity userEntity, Long companyId) {
CompanyEntity companyEntity = validateCompany(companyId);
companyRepository.delete(companyEntity);
userWithCompanyRepository.deleteByCompanyId(companyId);
userWithCompanyRepository.deleteByCompanyIdAndIsDeletedFalse(companyId);
}
public List<CompanyResponse> getCompanyByUserId(Long userId) {
UserEntity userEntity = userService.validateUser(userId);
List<Long> companyIds = userWithCompanyRepository.findCompanyIdByUserId(userEntity.getId());
List<CompanyEntity> list = companyRepository.findByIdIn(companyIds);
return list.stream().map(companyEntity->{
List<Long> activeCompanyIds = userWithCompanyRepository.findActiveCompanyIdsByUserId(userEntity.getId());
List<CompanyEntity> companies = companyRepository.findByIdInAndHubId(activeCompanyIds, userEntity.getHub().getId());
return companies.stream().map(companyEntity -> {
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyEntity.getId());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}).toList();
}
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
}
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, compnayId).orElseThrow(
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, compnayId).orElseThrow(
() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_COMPANY_RELATION_NOT_FOUND)));
}
public void removeCompanyFromList(UserEntity userEntity, Long companyId) {
CompanyEntity companyEntity = validateCompany(companyId);
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), companyEntity.getId())
.orElseThrow(() -> new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY)));
List<ApplicationEntity> userApplications = applicationRepository.findByCompanyIdAndUserIdAndIsDeletedFalse(companyEntity.getId(), userEntity.getId());
List<FaqEntity> faqs = faqRepository.findByCompanyIdAndUserIdAndIsDeletedFalse(companyEntity.getId(), userEntity.getId());
for (ApplicationEntity application : userApplications) {
if(Boolean.TRUE.equals(application.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT));
}
if(Boolean.TRUE.equals(application.getStatus().equals(ApplicationStatusTypeEnum.DRAFT.getValue()))) {
application.setIsDeleted(Boolean.TRUE);
applicationRepository.save(application);
}
}
for(FaqEntity faq:faqs) {
faq.setIsDeleted(Boolean.TRUE);
faqRepository.save(faq);
}
existingRelation.setIsDeleted(Boolean.TRUE);
userWithCompanyRepository.save(existingRelation);
}
}

View File

@@ -32,23 +32,23 @@ public class DashboardDao {
@Autowired
private CompanyRepository companyRepository;
public SuperAdminWidgetResponseBean getDashboardWidget() {
public SuperAdminWidgetResponseBean getDashboardWidget(UserEntity requestedUserEntity) {
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
widgetResponseBean.setWidget1(createWidget1());
widgetResponseBean.setWidget1(createWidget1(requestedUserEntity));
// List<Object[]> widgetBars = callRepository.findApplicationsPerCall();
// widgetResponseBean.setWidgetBars(widgetBars);
return widgetResponseBean;
}
private Widget1 createWidget1() {
private Widget1 createWidget1(UserEntity requestedUserEntity) {
Widget1 widget1 = initializeWidget1();
setActiveCalls(widget1);
setRegisteredUsers(widget1);
setTotalActiveFinancing(widget1);
setSubmittedApplications(widget1);
setDraftApplications(widget1);
setNumberOfCompanies(widget1);
setActiveCalls(widget1, requestedUserEntity);
setRegisteredUsers(widget1, requestedUserEntity);
setTotalActiveFinancing(widget1, requestedUserEntity);
setSubmittedApplications(widget1, requestedUserEntity);
setDraftApplications(widget1, requestedUserEntity);
setNumberOfCompanies(widget1, requestedUserEntity);
return widget1;
}
@@ -59,42 +59,42 @@ public class DashboardDao {
.build();
}
private void setActiveCalls(Widget1 widget1) {
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
private void setActiveCalls(Widget1 widget1, UserEntity requestedUserEntity) {
Long activeCalls = callRepository.countByStatusAndHubId(CallStatusEnum.PUBLISH.getValue(), requestedUserEntity.getHub().getId());
if (activeCalls != null) {
widget1.setNumberOfActiveCalls(activeCalls);
}
}
private void setRegisteredUsers(Widget1 widget1) {
Long activeUsers = userRepository.countByStatusAndRoleEntity_RoleType(UserStatusEnum.ACTIVE.getValue(),
RoleStatusEnum.ROLE_BENEFICIARY.getValue());
private void setRegisteredUsers(Widget1 widget1, UserEntity requestedUserEntity) {
Long activeUsers = userRepository.countByStatusAndRoleEntityRoleTypeAndHubId(UserStatusEnum.ACTIVE.getValue(),
RoleStatusEnum.ROLE_BENEFICIARY.getValue(), requestedUserEntity.getHub().getId());
if (activeUsers != null) {
widget1.setNumberOfResgisteredUsers(activeUsers);
}
}
private void setTotalActiveFinancing(Widget1 widget1) {
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCalls();
private void setTotalActiveFinancing(Widget1 widget1, UserEntity requestedUser) {
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCallsAndHubId(requestedUser.getHub().getId());
widget1.setTotalActiveFinancing(totalActiveFinancing);
}
private void setSubmittedApplications(Widget1 widget1) {
Long submittedApplications = applicationRepository.countSubmittedApplications();
private void setSubmittedApplications(Widget1 widget1, UserEntity requestedUserEntity) {
Long submittedApplications = applicationRepository.countSubmittedApplicationsByHubId(requestedUserEntity.getHub().getId());
if (submittedApplications != null) {
widget1.setNumberOfSubmittedApplications(submittedApplications);
}
}
private void setDraftApplications(Widget1 widget1) {
Long draftApplications = applicationRepository.countDraftApplications();
private void setDraftApplications(Widget1 widget1, UserEntity requestedUserEntity) {
Long draftApplications = applicationRepository.countDraftApplicationsByHubId(requestedUserEntity.getHub().getId());
if (draftApplications != null) {
widget1.setNumberOfDraftApplications(draftApplications);
}
}
private void setNumberOfCompanies(Widget1 widget1) {
Long numberOfCompanies = companyRepository.countTotalCompanies();
private void setNumberOfCompanies(Widget1 widget1, UserEntity requestedUserEntity) {
Long numberOfCompanies = companyRepository.countTotalCompaniesByHubId(requestedUserEntity.getHub().getId());
if (numberOfCompanies != null) {
widget1.setNumberOfCompany(numberOfCompanies);
}
@@ -104,7 +104,7 @@ public class DashboardDao {
CompanyEntity company) {
BeneficiaryWidgetResponseBean beneficiaryWidgetResponseBean = BeneficiaryWidgetResponseBean.builder()
.numberOfApplications(0L).numberOfCalls(0L).numberOfIntegratedDocuments(0L).build();
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
Long activeCalls = callRepository.countByStatusAndHubId(CallStatusEnum.PUBLISH.getValue(), userEntity.getHub().getId());
if (activeCalls != null) {
beneficiaryWidgetResponseBean.setNumberOfCalls(activeCalls);
}

View File

@@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
@@ -31,6 +32,7 @@ import net.gepafin.tendermanagement.service.AmazonS3Service;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -38,7 +40,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@Component
public class DelegationDao {
private static final String DEFAULT_PLACEHOLDER = "____________________";
// private static final String DEFAULT_PLACEHOLDER = "____________________";
@Autowired
private UserService userService;
@@ -58,6 +60,9 @@ public class DelegationDao {
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
@Autowired
private Validator validator;
public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) {
try {
@@ -89,9 +94,10 @@ public class DelegationDao {
return new XWPFDocument(templateStream);
}
public ByteArrayOutputStream downloadCompanyDelegation(UserEntity userEntity, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
public ByteArrayOutputStream downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
Map<String, String> placeholders = getDefaultPlaceholders();
UserResponseBean user = userService.getUserById(userEntity.getId());
UserEntity userEntity = validator.validateUser(request);
UserResponseBean user = userService.getUserById(request, userEntity.getId());
CompanyEntity companyEntity = companyDao.validateCompany(companyId);
companyDao.getUserWithCompany(userEntity.getId(), companyId);
updatePlaceholdersForDelegation(user, companyEntity, placeholders, companyDelegationRequest);

View File

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

View File

@@ -6,25 +6,27 @@ import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.ContentResponseBean;
import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.model.response.VatNumberResponseBean;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.EvaluationCriteriaService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Component
@@ -33,9 +35,6 @@ public class FormDao {
@Autowired
private FormRepository formRepository;
@Autowired
private CallService callService;
@Autowired
private ApplicationFormRepository applicationFormRepository;
@@ -54,14 +53,22 @@ public class FormDao {
@Autowired
private CallRepository callRepository;
@Autowired
private Validator validator;
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
@Autowired
private EvaluationCriteriaService evaluationCriteriaService;
public FormEntity saveFormEntity(FormEntity formEntity){
formEntity=formRepository.save(formEntity);
return formEntity;
}
public FormEntity convertFormRequestToFormEntity(Long callId,FormRequest formRequest){
public FormEntity convertFormRequestToFormEntity(CallEntity callEntity, FormRequest formRequest){
FormEntity formEntity=new FormEntity();
CallEntity callEntity=callService.getCallEntityById(callId);
formEntity.setCall(callEntity);
formEntity.setLabel(formRequest.getLabel());
formEntity.setContent(setContentResponseBean(formRequest.getContent()));
@@ -71,17 +78,29 @@ public class FormDao {
public FormResponseBean convertFormEntityToFormResponseBean(FormEntity formEntity) {
FormResponseBean formResponseBean=new FormResponseBean();
formResponseBean.setId(formEntity.getId());
formResponseBean.setContent(Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class));
formResponseBean.setContent(setContent(formEntity));
formResponseBean.setLabel(formEntity.getLabel());
formResponseBean.setCallId(formEntity.getCall().getId());
formResponseBean.setCallStatus(formEntity.getCall().getStatus());
return formResponseBean;
}
public FormResponseBean createForm(Long callId,FormRequest formRequest){
private List<ContentResponseBean> setContent(FormEntity formEntity) {
List<ContentResponseBean> contentList = Utils.convertJsonStringToList(formEntity.getContent(),
ContentResponseBean.class);
contentList.forEach(data -> {
List<Long> criteriaIds = criteriaFormFieldRepository
.findByCallIdAndFormIdAndFormFieldIdAndIsDeletedFalse(formEntity.getCall().getId(), formEntity.getId(), data.getId())
.stream().map(CriteriaFormFieldEntity::getEvaluationCriteriaId).toList();
data.setCriteria(criteriaIds);
});
return contentList;
}
public FormResponseBean createForm(CallEntity callEntity,FormRequest formRequest){
validateForm(formRequest);
CallEntity callEntity=callService.validateCall(callId);
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callId);
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callId);
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callEntity.getId());
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callEntity.getId());
if(Boolean.FALSE.equals(flowDataEntities.isEmpty() || flowDataEntities==null ) || Boolean.FALSE.equals(flowEdgesEntities.isEmpty() || flowEdgesEntities==null) ){
flowDataRepository.deleteAll(flowDataEntities);
flowEdgesRepository.deleteAll(flowEdgesEntities);
@@ -89,18 +108,71 @@ public class FormDao {
callEntity.setFinalForm(null);
callRepository.save(callEntity);
}
FormEntity formEntity=convertFormRequestToFormEntity(callId,formRequest);
FormEntity formEntity=convertFormRequestToFormEntity(callEntity, formRequest);
validateAndSaveCriteriaFormField(callEntity, formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity);
}
private void validateAndSaveCriteriaFormField(CallEntity callEntity, FormEntity formEntity,
List<ContentRequestBean> contentResponseBeans) {
contentResponseBeans.forEach(content -> {
// Fetch existing records from the repository based on the call, form, and field ID
List<CriteriaFormFieldEntity> existingCriteriaFields = criteriaFormFieldRepository
.findByCallIdAndFormIdAndFormFieldIdAndIsDeletedFalse(callEntity.getId(), formEntity.getId(), content.getId());
// Extract existing evaluation criteria IDs into a set for quick lookup
Set<Long> existingEvaluationCriteriaIds = existingCriteriaFields.stream()
.map(CriteriaFormFieldEntity::getEvaluationCriteriaId)
.collect(Collectors.toSet());
// Get the criteria list (handling null as an empty list for uniformity)
List<Long> criteriaList = Optional.ofNullable(content.getCriteria()).orElse(Collections.emptyList());
// Filter and create new entries for criteria that are not already present
criteriaList.stream()
.filter(criteriaId -> !existingEvaluationCriteriaIds.contains(criteriaId))
.forEach(criteriaId -> createCriteriaFormField(callEntity, formEntity, content.getId(), criteriaId));
List<CriteriaFormFieldEntity> toBeDeleted = existingCriteriaFields.stream()
.filter(criteriaFormField -> !criteriaList.contains(criteriaFormField.getEvaluationCriteriaId()))
.peek(data->data.setIsDeleted(Boolean.TRUE))
.collect(Collectors.toList());
if (!toBeDeleted.isEmpty()) {
criteriaFormFieldRepository.saveAll(toBeDeleted);
}
});
}
private void createCriteriaFormField(CallEntity callEntity, FormEntity formEntity,
String formFieldId,Long evaluationCriteriaId) {
EvaluationCriteriaEntity evaluationCriteria = evaluationCriteriaService.validateEvaluationCriteria(evaluationCriteriaId);
if (Boolean.FALSE.equals(evaluationCriteria.getCall().getId().equals(callEntity.getId()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.EVALUATIONCRITERIA_INVALID));
}
CriteriaFormFieldEntity criteriaFormField = new CriteriaFormFieldEntity();
criteriaFormField.setCallId(callEntity.getId());
criteriaFormField.setFormId(formEntity.getId());
criteriaFormField.setFormFieldId(formFieldId);
criteriaFormField.setIsDeleted(Boolean.FALSE);
criteriaFormField.setEvaluationCriteriaId(evaluationCriteriaId);
criteriaFormFieldRepository.save(criteriaFormField);
}
public void validateForm(FormRequest formRequest){
if(formRequest.getContent()==null || formRequest.getLabel()==null ){
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.REQUIRED_PARAMETER_NOT_FOUND_FOR_FORM));
}
}
public FormResponseBean updateForm(Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
public FormResponseBean updateForm(UserEntity user, Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
ContentRequestBean contentRequestBean2=null;
String choosenField=null;
FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
callDao.validateUpdate(formEntity.getCall());
List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(), ContentRequestBean.class);
for (ContentRequestBean contentRequestBean1 : contentRequestBean) {
@@ -160,6 +232,7 @@ public class FormDao {
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
validateAndSaveCriteriaFormField(formEntity.getCall(), formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity);
}
return convertFormEntityToFormResponseBean(formEntity);
@@ -171,12 +244,14 @@ public class FormDao {
return formEntity;
}
public FormResponseBean getFormEntityById(Long formId) {
public FormResponseBean getFormEntityById(UserEntity user, Long formId) {
FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
return convertFormEntityToFormResponseBean(formEntity);
}
public void deleteFormById(Long formId){
public void deleteFormById(UserEntity user, Long formId){
FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(formEntity.getCall().getId());
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(formEntity.getCall().getId());
flowDataRepository.deleteAll(flowDataEntities);
@@ -187,20 +262,22 @@ public class FormDao {
callRepository.save(callEntity);
formRepository.delete(formEntity);
}
public List<FormResponseBean> getFormsByCallId(Long callId){
CallEntity callEntity=callService.validateCall(callId);
public List<FormResponseBean> getFormsByCallId(CallEntity callEntity){
if(callEntity== null){
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
}
List<FormEntity> formEntities=formRepository.findByCallId(callId);
List<FormEntity> formEntities=formRepository.findByCallId(callEntity.getId());
List<FormResponseBean> formResponseBeanList = formEntities.stream()
.map(req -> convertFormEntityToFormResponseBean(req))
.collect(Collectors.toList());
return formResponseBeanList;
}
public String setContentResponseBean(List<ContentRequestBean> contentRequestBeans){
return Utils.convertListToJsonString(contentRequestBeans);
String stringContentRequest = Utils.convertListToJsonString(contentRequestBeans);
List<ContentRequestBean> cloneContentRequestBeans = Utils.convertJsonStringToList(stringContentRequest, ContentRequestBean.class);
cloneContentRequestBeans.forEach(data->data.setCriteria(null));
return Utils.convertListToJsonString(cloneContentRequestBeans);
}
public void validateFormField(List<ApplicationFormFieldRequestBean> applicationFormFieldRequestList, ApplicationEntity applicationEntity, FormEntity formEntity) {
@@ -295,12 +372,13 @@ public class FormDao {
String error=null;
if (value!=null && value.matches("^\\d{1,11}$")) {
Map<String, Object> customData=null;
// Map<String, Object> customData=null;
try {
Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
customData = vatCheckResponse;
}
// Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
vatCheckDao.checkVatNumberApi(value);
// if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
// customData = vatCheckResponse;
// }
} catch (Exception e) {
error=(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_VALID_PIVA), fieldId));
}

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

@@ -0,0 +1,58 @@
package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.response.LoginAttemptPageableResponseBean;
import net.gepafin.tendermanagement.repositories.LoginAttemptRepository;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Component
public class LoginAttemptDao {
@Autowired
LoginAttemptRepository loginAttemptRepository;
public void createLoginAttempt(LoginAttemptEntity loginAttemptEntity) {
loginAttemptEntity.setAttemptDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
loginAttemptRepository.save(loginAttemptEntity);
}
public LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(UserEntity userEntity, Integer pageNo, Integer pageLimit) {
if (pageLimit == null || pageLimit <= 0) {
pageLimit = GepafinConstant.DEFAULT_PAGE_LIMIT;
}
if (pageNo == null || pageNo <= 0) {
pageNo = GepafinConstant.DEFAULT_PAGE;
}
Page<LoginAttemptEntity> page = loginAttemptRepository.findByHubId(userEntity.getHub().getId(), PageRequest.of(pageNo - 1, pageLimit, Sort.by(GepafinConstant.ATTEMPT_DATE).descending()));
List<LoginAttemptEntity> list = new ArrayList<>();
for (LoginAttemptEntity loginAttemptEntity : page.getContent()) {
list.add(loginAttemptEntity);
}
LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> pageableResponseBean = new LoginAttemptPageableResponseBean<>();
pageableResponseBean.setBody(list);
pageableResponseBean.setCurrentPage(page.getNumber() + 1);
pageableResponseBean.setTotalPages(page.getTotalPages());
pageableResponseBean.setTotalRecords(page.getTotalElements());
pageableResponseBean.setPageSize(page.getSize());
pageableResponseBean.setStatus(Status.SUCCESS);
pageableResponseBean.setMessage(Translator.toLocale(GepafinConstant.GET_LOGIN_ATTEMPT_MSG));
return pageableResponseBean;
}
}

View File

@@ -2,12 +2,6 @@ package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.text.*;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
@@ -16,28 +10,21 @@ import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import lombok.extern.slf4j.Slf4j;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.model.request.CustomPageEvent;
import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Cell;
//import com.itextpdf.layout.element.
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
@@ -54,6 +41,7 @@ public class PdfDao {
@Autowired
private Validator validator;
public static final Logger log = LoggerFactory.getLogger(PdfDao.class);
public byte[] generatePdf(HttpServletRequest request,Long applicationId) {
try {
@@ -92,56 +80,11 @@ public class PdfDao {
addColoredLines(writer,document,greyColor);
document.add(new Paragraph(" "));
// Application ID section (Centered)
// pageEvent.setTotalPages(writer.getPageNumber());
String protocolNumber="XX00";
if(applicationEntity.getProtocol()!=null) {
protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
}
Paragraph appId = new Paragraph("ID domanda :" +protocolNumber);
appId.setAlignment(Element.ALIGN_RIGHT);
document.add(appId);
document.add(new Paragraph(" "));
addColoredLines(writer,document,greenColor);
document.add(new Paragraph(" "));
document.add(new Paragraph("\n")); // Add line break
// String companyName= companyEntity.getCompanyName();
// String vatNumber=companyEntity.getVatNumber();
// String address=companyEntity.getAddress();
// // Section: Dati Anagrafici Azienda
// document.add(new Paragraph("Dati Anagrafici Azienda", sectionFont));
// addLabelValuePair(document, "Codice ATECO", "SEZIONE C “ATTIVITÀ MANUFATTURIERE”", regularFont);
// addLabelValuePair(document, "Ragione Sociale", companyName, regularFont);
// addLabelValuePair(document, "Partita IVA", vatNumber, regularFont);
// addLabelValuePair(document, "Indirizzo sede Legale", address, regularFont);
//
// document.add(new Paragraph("\n")); // Add line break
//
// // Section: Domanda presentata da
// document.add(new Paragraph("Domanda presentata da:", sectionFont));
// addLabelValuePair(document, "Nome e cognome", userEntity.getBeneficiary().getFirstName()+" "+userEntity.getBeneficiary().getLastName(), regularFont);
// addLabelValuePair(document, "Codice fiscale", userEntity.getBeneficiary().getCodiceFiscale(), regularFont);
// addLabelValuePair(document, "Telefono", userEntity.getBeneficiary().getPhoneNumber(), regularFont);
// addLabelValuePair(document, "Email", userEntity.getBeneficiary().getEmail(), regularFont);
// addLabelValuePair(document, "Con il titolo di", "Rappresentante legale", regularFont);
document.add(new Paragraph(" "));
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(applicationId,null, userEntity);
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(request, applicationId, null);
for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) {
document.add(new Paragraph(formApplicationResponse.getLabel(),sectionFont));
document.add(new Paragraph(" ")); // Add line break
List<FieldLabelValuePairRequest> fieldLabelValuePairRequests = getFormFieldsToLabels(formApplicationResponse);
for (FieldLabelValuePairRequest pair : fieldLabelValuePairRequests) {
String label = pair.getLabel();
Object value = pair.getValue();
Integer pages=0;
pages=addLabelValuePair(writer,document, label, value, labelFont,valueFont,call.getName(),pages);
if(pages !=0 ){
// pageEvent.setTotalPages(writer.getPageNumber());
}
}
List<FieldLabelValuePairRequest> fieldLabelValuePairRequests = getFormFieldsToLabels(formApplicationResponse,writer,document);
addColoredLines(writer,document,greenColor);
document.add(new Paragraph(" ")); // Add line break
}
@@ -217,15 +160,6 @@ public class PdfDao {
addColoredLines(writer,document,greenColor);
// System.out.println(writer.getPageSize());
// System.out.println(document.getPageSize());
// System.out.println(document.getPageNumber());
// System.out.println(writer.getPageNumber());
// document.setPageCount(100);
// document.setPageCount(writer.getPageNumber());
// System.out.println(document.getPageNumber());
// Close the document
document.close();
// Convert to byte array for response
@@ -238,12 +172,13 @@ public class PdfDao {
return null;
}
private Integer addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,String title,Integer totalPages) throws DocumentException {
private void addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,ContentResponseBean contentResponseBean) throws DocumentException {
// Add label
Map<String, Boolean> stateFieldMap= new HashMap<>();
Paragraph labelParagraph = new Paragraph(label, labelFont);
document.add(labelParagraph);
float leftMargin = 20f;
PdfContentByte canvas = writer.getDirectContent();
// Setting the color and width of the line
@@ -257,8 +192,6 @@ public class PdfDao {
if (yPos <= 140) {
// If xEnd is less than or equal to 200, generate a new page
totalPages++;
document.newPage();
} // Add a gap between the label and value
document.add(new Paragraph(" ")); // Adding an empty paragraph for spacing
@@ -288,44 +221,13 @@ public class PdfDao {
// Finally, add the table to the document
document.add(valueTable);
} else {
boolean containsThreeValues = false; // Variable to track if any map contains three keys
List<Map<String, Object>> dataList = (List<Map<String, Object>>) value; // Cast Object to List of Maps
for (Map<String, Object> entry : dataList) {
if (entry.size() == 3) { // Check if the current map has three keys
containsThreeValues = true; // If found, set the variable to true
break; // No need to check further, exit loop
}
}
List<Map<String, String>> extractedData = new ArrayList<>(); // To hold extracted data
for (Map<String, Object> entry : dataList) {
Map<String, String> extractedMap = new HashMap<>(); // To hold the current extracted row of data
else if (!list.isEmpty() && list.get(0) instanceof Map<?, ?>) {
Object object = value;
String stringvalue = Utils.convertToString(object);
List<Map<String, Object>> fieldValueList = Utils.convertJsonStringIntoJsonList(stringvalue);
List<String> keys = new ArrayList<>(entry.keySet()); // Get all keys in the current map
// Handle based on the number of keys in the map
if (Boolean.FALSE.equals(containsThreeValues) && keys.size() == 2) {
// Treat the first key as the "key" and second key as the "value"
String heading = (String) entry.get(keys.get(0)); // Get value of first key
String value1 = (String) entry.get(keys.get(1)); // Get value of second key
extractedMap.put(heading,value1); // Store the first key's value as "heading"
} if (Boolean.TRUE.equals(containsThreeValues) ) {
String amount="";
// Treat the first as number, second as description, third as amount
if(keys.size()==3){
amount = (String) entry.get(keys.get(2)); // Third key's value
}
String number = (String) entry.get(keys.get(0)); // First key's value
String description = (String) entry.get(keys.get(1)); // Second key's value
// Store the combined result as a value in the map, with a suitable key
String combinedValue = number + "; " + description + "; " + amount; // Concatenate them as a single value
extractedMap.put("combined", combinedValue); // Store as a single entry, key as "combined"
}
extractedData.add(extractedMap); // Add each extracted map to the list
}
document=createPdfTable(extractedData,document);
document = createPdfTable(fieldValueList, document, contentResponseBean);
}
}
else {
@@ -342,150 +244,89 @@ public class PdfDao {
}
document.add(new Paragraph("\n")); // Add line break after each value
return totalPages;
}
private Document createPdfTable(List<Map<String, String>> extractedData,Document document) throws DocumentException {
// Create a PdfPTable with 2 columns
PdfPTable table = new PdfPTable(2); // Initial assumption for 2 columns
private Document createPdfTable(List<Map<String, Object>> extractedData, Document document, ContentResponseBean contentResponseBean) throws DocumentException {
// Create a PdfPTable with dynamic column count based on stateFieldMap size
Map<String, String> stateFieldMap = new HashMap<>();
// Populate stateFieldMap from contentResponseBean settings
contentResponseBean.getSettings().stream()
.filter(setting -> "table_columns".equals(setting.getName())) // Check for "table_columns"
.map(SettingResponseBean::getValue)
.filter(Objects::nonNull) // Ensure value is not null
.filter(settingValue -> settingValue instanceof Map) // Ensure value is a Map
.map(settingValue -> (Map<String, Object>) settingValue) // Cast to Map
.map(valueMap -> (List<Map<String, Object>>) valueMap.get("stateFieldData")) // Extract stateFieldData list
.filter(Objects::nonNull) // Ensure stateFieldData is not null
.flatMap(List::stream) // Flatten the list of field data maps
.forEach(fieldData -> {
String fieldName = (String) fieldData.get("name"); // Get the name field
String fieldDataValue = (String) fieldData.get("label"); // Get the predefined field
if (fieldName != null && fieldDataValue != null) {
stateFieldMap.put(fieldName, fieldDataValue);
}
});
PdfPTable table = new PdfPTable(stateFieldMap.size()); // Number of columns equals the number of map entries
table.setWidthPercentage(100); // Set table width to 100%
table.setTableEvent(new RoundedBorderEvent());
Font textFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new BaseColor(105, 105, 105)); // Gray text
boolean combinedHeaderAdded = false; // Flag to track if headers for combined have been added
float rowHeight = 50f; // Example row height, adjust as necessary
float rowHeight = 20f; // Example row height
float maxTableHeight = 700f; // Maximum height of the table before a page break
float[] columnWidths = {0.7f, 0.3f};
table.setWidths(columnWidths);
boolean headersAdded = false; // Flag to check if headers have been added
// Iterate through extracted data to populate the table
for (Map<String, Object> row : extractedData) {
// Add headers once
if (!headersAdded) {
for (Map.Entry<String, String> stateField : stateFieldMap.entrySet()) {
String headerValue = stateField.getValue(); // Header text
// Add table header
// Populate the table with extracted data and style rows
for (Map<String, String> row : extractedData) {
for (Map.Entry<String, String> entry : row.entrySet()) {
String key = entry.getKey(); // This will give you the key
String value = entry.getValue(); // This will give you the value
PdfPCell headerCell = new PdfPCell(new Phrase(headerValue)); // Create a new PdfPCell for the header
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
// Check if the current entry is for the combined section
if ("combined".equals(key)) {
// Ensure the combined header is added only once
if (!combinedHeaderAdded) {
// Create a new table for combined entries
table = new PdfPTable(3); // 3 columns for combined entries
PdfPCell headerCell1 = new PdfPCell(new Phrase("Number"));
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell1);
PdfPCell headerCell2 = new PdfPCell(new Phrase("Details"));
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell2);
PdfPCell headerCell3 = new PdfPCell(new Phrase("Amount"));
headerCell3.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell3.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell3);
combinedHeaderAdded = true; // Mark header as added
table.addCell(headerCell); // Add the header cell to the table
}
headersAdded = true; // Prevent headers from being added again
}
// Split the value for "combined" into separate parts
String[] combinedValues = value.split("; ");
// Add data rows matching stateFieldMap keys
for (Map.Entry<String, String> stateField : stateFieldMap.entrySet()) {
String stateKey = stateField.getKey(); // Get the key from stateFieldMap
if (row.containsKey(stateKey)) { // If row contains the stateKey
Object value = row.get(stateKey); // Get the value from the row map
// Check if we have 3 parts (number, description, amount)
String number = combinedValues[0]; // 1st part (number)
String description = combinedValues[1]; // 2nd part (description)
String amount = "";
if (combinedValues.length == 3) {
amount = combinedValues[2]; // 3rd part (amount)
PdfPCell dynamicCell = new PdfPCell(new Phrase(value != null ? value.toString() : "", textFont));
dynamicCell.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for the cell
dynamicCell.setMinimumHeight(rowHeight);
dynamicCell.setPadding(7f);
table.addCell(dynamicCell); // Add the dynamically created cell to the table
}
}
// Create PDF cells using the split values
PdfPCell cellNumber = new PdfPCell(new Phrase(number, textFont)); // Cell for number
PdfPCell cellDescription = new PdfPCell(new Phrase(description, textFont)); // Cell for description
PdfPCell cellAmount = new PdfPCell(new Phrase(amount, textFont)); // Cell for amount
// Set row background color for combined values
cellNumber.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for combined rows
cellDescription.setBackgroundColor(new BaseColor(239, 243, 248));
cellAmount.setBackgroundColor(new BaseColor(239, 243, 248));
// Set cell height and add rounded borders
// cellNumber.setFixedHeight(rowHeight);
// cellDescription.setFixedHeight(rowHeight);
// cellAmount.setFixedHeight(rowHeight);
cellNumber.setMinimumHeight(20f); // Set minimum height for better appearance
cellDescription.setMinimumHeight(20f); // Set minimum height for better appearance
cellAmount.setMinimumHeight(20f); // Set minimum height for better appearance
cellNumber.setPadding(7f);
cellDescription.setPadding(7f);
cellAmount.setPadding(7f);
// Add the cells to the table only once
table.addCell(cellNumber);
table.addCell(cellDescription);
table.addCell(cellAmount);
} else {
if (!combinedHeaderAdded) {
// Create a new table for combined entries
table= new PdfPTable(2); // 3 columns for combined entries
table.setWidthPercentage(100);
PdfPCell headerCell1 = new PdfPCell(new Phrase("Details"));
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell1);
PdfPCell headerCell2 = new PdfPCell(new Phrase("Amount"));
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell2);
combinedHeaderAdded=true;
}
// Add cells for regular key-value pairs without headers
PdfPCell cellKey = new PdfPCell(new Phrase(key, textFont));
PdfPCell cellValue = new PdfPCell(new Phrase(value, textFont));
// Set background color for both cells
cellKey.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for other rows
cellValue.setBackgroundColor(new BaseColor(239, 243, 248));
cellKey.setPadding(7f);
cellValue.setPadding(7f);
// Set cell height and add rounded borders
cellKey.setFixedHeight(rowHeight);
cellValue.setFixedHeight(rowHeight);
// Add the cells to the table
table.addCell(cellKey);
table.addCell(cellValue);
}
// Check if adding another row would exceed max height
if (table.getTotalHeight() + rowHeight > maxTableHeight) {
// Start a new page if needed
document.add(table); // Add the table to the document
document.newPage(); // Start a new page
table = new PdfPTable(stateFieldMap.size()); // Create a new table for the new page
table.setWidthPercentage(100); // Reset table width
headersAdded = false; // Reset the header flag for the new page
}
}
// Add the last table to the document
document.add(table);
table = new PdfPTable(2); // Reset table for new page
table.setWidthPercentage(100); // Reset width percentage
combinedHeaderAdded = false; // Reset header flag
}
}
}
document.add(table); // Add the last table before returning
// Check if adding a new row would exceed the maximum height
// Return the populated table
return document;
}
public static class RoundedBorderEvent implements PdfPTableEvent {
@Override
public void tableLayout(PdfPTable table, float[][] widths, float[] heights,
@@ -506,83 +347,99 @@ public class PdfDao {
canvas.stroke();
}
}
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean) {
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean,PdfWriter writer,Document document) {
List<FieldLabelValuePairRequest> labelValuePairs = new ArrayList<>();
// Iterate through each form in the application response
Font labelFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,new BaseColor(113,121,126)); // Light grey);
Font valueFont=FontFactory.getFont(FontFactory.HELVETICA_BOLD,10,new BaseColor(178, 190, 181));
// Get form fields and contents from the response
List<ApplicationFormFieldResponseBean> formFields = responseBean.getFormFields();
List<ContentResponseBean> contents = responseBean.getContent();
// Iterate through each formField in the current form
for (ApplicationFormFieldResponseBean formField : formFields) {
String fieldId = formField.getFieldId();
Object fieldValue = formField.getFieldValue();
// Iterate through each content in the response
for (ContentResponseBean content : contents) {
String contentId = content.getId(); // Content ID
String label = content.getLabel(); // Content label
String name = content.getName(); // Content name
Object fieldValue = null;
// Find the content in the form that matches the fieldId
Optional<ContentResponseBean> matchingContent = contents.stream()
.filter(content -> content.getId().equals(fieldId))
String contentLabel = content.getSettings().stream()
.filter(setting -> "label".equals(setting.getName())) // Filter settings by name
.map(SettingResponseBean::getValue) // Extract the value from the matching setting
.map(Object::toString) // Convert the value to a string
.findFirst() // Get the first matching value
.orElse(null); // If no match is found, set label to null
// Find the form field in the response that matches the contentId
Optional<ApplicationFormFieldResponseBean> matchingFormField = formFields.stream()
.filter(formField -> formField.getFieldId().equals(contentId))
.findFirst();
// If a matching form field is found, process its value
if (matchingFormField.isPresent()) {
ApplicationFormFieldResponseBean formField = matchingFormField.get();
fieldValue = formField.getFieldValue();
// If the content with the matching fieldId is found, create a label-value pair
if (matchingContent.isPresent()) {
String name = matchingContent.get().getName();
// If fieldValue is null, set it to an empty string
if (fieldValue == null) {
fieldValue = "";
}
// Process 'fileupload' and 'checkboxes' cases as in the original logic
if (name.equals("fileupload")) {
// Step 1: Check if fieldValue is an instance of List<DocumentResponseBean>
if (fieldValue instanceof List<?> && ((List<?>) fieldValue).stream().allMatch(item -> item instanceof DocumentResponseBean)) {
// Step 2: Safely cast to List<DocumentResponseBean>
List<DocumentResponseBean> documentList = (List<DocumentResponseBean>) fieldValue;
// Step 3: Extract names from the document list
List<String> names = documentList.stream()
.map(DocumentResponseBean::getName) // Extract the name from each DocumentResponseBean
.map(DocumentResponseBean::getName)
.collect(Collectors.toList());
fieldValue = names;
}
}
if(name.equals("checkboxes")) {
} else if (name.equals("checkboxes")) {
List<String> check = (List<String>) fieldValue;
List<SettingResponseBean> settingResponseBeans = matchingContent.get().getSettings();
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
// Initialize a list to hold matched labels for each SettingResponseBean
List<SettingResponseBean> settingResponseBeans = content.getSettings();
List<String> matchedLabels = new ArrayList<>();
if (settingResponseBean.getValue() instanceof List<?>) {
List<?> valueList = (List<?>) settingResponseBean.getValue();
if (!valueList.isEmpty() && valueList.get(0) instanceof Map<?, ?>) {
// Cast to List<Map<String, String>>
List<Map<String, String>> options = (List<Map<String, String>>) valueList;
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
if (settingResponseBean.getValue() instanceof List<?>) {
List<Map<String, String>> options = (List<Map<String, String>>) settingResponseBean.getValue();
for (Map<String, String> field : options) {
for (String val : check) {
String name1 = field.get("name");
if (val.equals(name1)) { // Check if the key exists in the current field map
String label = field.get("label"); // Extract the label
if (field != null) { // Check if the value is not null
matchedLabels.add(label); // Add the value to the matchedValues list
if (val.equals(name1)) {
String labelVal = field.get("label");
if (labelVal != null) {
matchedLabels.add(labelVal);
}
}
}
}
}
}
fieldValue = matchedLabels;
}
// Further processing of field value (e.g., finding labels in options)
fieldValue = findLabelInOptions(content.getSettings(), fieldValue);
} else {
// If no matching form field is found, store contentId with an empty string
fieldValue = "";
}
try {
addLabelValuePair(writer,document, contentLabel, fieldValue, labelFont,valueFont,content);
} catch (DocumentException e) {
log.error("Error checking object: " + e.getMessage(), e);
}
}
String label = matchingContent.get().getLabel();
// Add the label-value pair to the list
if (fieldValue != null && !fieldValue.toString().trim().isEmpty()) {
fieldValue = findLabelInOptions(matchingContent.get().getSettings(), fieldValue);
labelValuePairs.add(new FieldLabelValuePairRequest(label, fieldValue));
}
}
// } labelValuePairs.add(new FieldLabelValuePairRequest(contentLabel, fieldValue));
}
return labelValuePairs;
}
public static Object findLabelInOptions(List<SettingResponseBean> settings, Object valueToFind) {
ObjectMapper objectMapper = new ObjectMapper();

View File

@@ -2,9 +2,11 @@ package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.RoleEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
@@ -17,9 +19,11 @@ import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.service.RoleService;
import net.gepafin.tendermanagement.service.impl.AuthenticationService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -28,12 +32,14 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
@@ -43,8 +49,10 @@ public class UserDao {
@Autowired
private UserRepository userRepository;
@Autowired
private CompanyDao companyDao;
@Autowired
private AuthenticationService authService;
@@ -57,19 +65,37 @@ public class UserDao {
@Autowired
private BeneficiaryRepository beneficiaryRepository;
@Autowired
private RoleService roleService;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
@Autowired
private Validator validator;
@Autowired
private SamlSuccessHandler samlSuccessHandler;
@Autowired
private HubService hubService;
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
validateUserRequest(tempToken, userReq);
if(StringUtils.isEmpty(userReq.getHubUuid())) {
userReq.setHubUuid(defaultHubUuid);
}
HubEntity hub = hubService.getHubByUuid(userReq.getHubUuid());
validateUserRequest(request, tempToken, userReq, hub);
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
RoleEntity roleEntity = getRoleEntity(userReq.getRoleId());
BeneficiaryEntity beneficiary = createBeneficiary(roleEntity, userReq);
UserEntity userEntity = convertUserRequestToUserEntity(beneficiary, roleEntity, userReq);
BeneficiaryEntity beneficiary = createBeneficiary(roleEntity, userReq, hub);
UserEntity userEntity = convertUserRequestToUserEntity(beneficiary, roleEntity, userReq, hub);
log.info("User created with ID: {}", userEntity.getId());
return authService.getJWTTokenBean(userEntity, Boolean.TRUE);
}
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq) {
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq, HubEntity hub) {
BeneficiaryEntity beneficiaryEntity = null;
if (RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType())) {
beneficiaryEntity = new BeneficiaryEntity();
@@ -89,24 +115,34 @@ public class UserDao {
beneficiaryEntity.setMarketing(userReq.getMarketing());
beneficiaryEntity.setThirdParty(userReq.getThirdParty());
beneficiaryEntity.setEmailPec(userReq.getEmailPec());
beneficiaryEntity.setHubId(hub.getId());
beneficiaryEntity =beneficiaryRepository.save(beneficiaryEntity);
}
return beneficiaryEntity;
}
private void validateUserRequest(String tempToken, UserReq userReq) {
private void validateUserRequest(HttpServletRequest request, String tempToken, UserReq userReq, HubEntity hub) {
if (tempToken == null) {
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
UserEntity userEntity = validator.validateUser(request);
userReq.setHubUuid(userEntity.getHub().getUniqueUuid());
}else {
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale(), userReq.getHubUuid());
}
if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
}
log.info("Creating user with email: {}", userReq.getEmail());
if (userRepository.existsByEmailIgnoreCase(userReq.getEmail())) {
if (userRepository.existsByEmailIgnoreCaseAndHubUniqueUuid(userReq.getEmail(), userReq.getHubUuid())) {
log.error("User creation failed: Email {} already exists", userReq.getEmail());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
}
if (Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getCodiceFiscale()))
&& userRepository.existsByBeneficiaryCodiceFiscale(userReq.getCodiceFiscale())) {
&& userRepository.existsByBeneficiaryCodiceFiscaleAndHubId(userReq.getCodiceFiscale(), hub.getId())) {
log.error("User creation failed: CodiceFiscale {} already exists", userReq.getCodiceFiscale());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CODICE_FISCALE_EXISTS));
@@ -118,6 +154,14 @@ public class UserDao {
if (tempToken != null) {
userReq.setRoleId(null);
}
if (tempToken == null) {
RoleEntity role = roleService.validateRole(userReq.getRoleId());
if (Boolean.TRUE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(role.getRoleType()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CANNOT_CREATE_BENEFICIARY_USER));
}
}
}
private void validatePassword(String password, String confirmPassword, String tempToken) {
@@ -169,7 +213,7 @@ public class UserDao {
return convertUserEntityToUserResponse(userEntity);
}
private UserEntity convertUserRequestToUserEntity(BeneficiaryEntity beneficiary, RoleEntity roleEntity, UserReq userReq) {
private UserEntity convertUserRequestToUserEntity(BeneficiaryEntity beneficiary, RoleEntity roleEntity, UserReq userReq, HubEntity hub) {
UserEntity userEntity = new UserEntity();
if(Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getPassword()))) {
userEntity.setPassword(passwordEncoder.encode(userReq.getPassword()));
@@ -178,8 +222,8 @@ public class UserDao {
userEntity.setEmail(userReq.getEmail());
userEntity.setStatus(UserStatusEnum.ACTIVE.getValue());
userEntity.setBeneficiary(beneficiary);
userEntity.setHub(hub);
if (Boolean.FALSE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType()))) {
userEntity.setFirstName(userReq.getFirstName());
userEntity.setLastName(userReq.getLastName());
userEntity.setOrganization(userReq.getOrganization());
@@ -257,9 +301,12 @@ public class UserDao {
log.info("User deleted with ID: {}", id);
}
public JWTToken login(LoginReq loginReq) {
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
log.info("User login attempt for email: {}", loginReq.getEmail());
JWTToken jwtToken = authService.login(loginReq);
if(StringUtils.isEmpty(loginReq.getHubUuid())) {
loginReq.setHubUuid(defaultHubUuid);
}
JWTToken jwtToken = authService.login(loginReq,request);
log.info("Login successful for email: {}", loginReq.getEmail());
return jwtToken;
}
@@ -279,11 +326,11 @@ public class UserDao {
}
public String initiatePasswordReset(InitiatePasswordResetReq resetReq) {
UserEntity user = userRepository.findByEmail(resetReq.getEmail());
if (user == null) {
log.info("Password reset attempt for non-existent user: {}", resetReq.getEmail());
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
UserEntity user = userRepository
.findByEmailIgnoreCaseAndHubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
String token = Utils.generateSecureToken();
user.setResetPasswordToken(token);
userRepository.save(user);
@@ -292,11 +339,11 @@ public class UserDao {
}
public Boolean resetPassword(ResetPasswordReq resetPasswordReq) {
UserEntity user = userRepository.findByEmail(resetPasswordReq.getEmail());
if (user == null) {
log.info("Password reset attempt for non-existent user: {}", resetPasswordReq.getEmail());
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
UserEntity user = userRepository
.findByEmailIgnoreCaseAndHubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
if (!resetPasswordReq.getNewPassword().equals(resetPasswordReq.getConfirmPassword())) {
log.info("User creation failed: Passwords do not match for email {}", user.getEmail());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
@@ -315,12 +362,12 @@ public class UserDao {
return true;
}
public Boolean changePassword(ChangePasswordRequest request) {
UserEntity user = userRepository.findByEmail(request.getEmail());
if (user == null) {
log.info("Password reset attempt for non-existent user: {}", request.getEmail());
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest request) {
UserEntity user = userRepository
.findByEmailIgnoreCaseAndHubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CURRENT_PASSWORD_INCORRECT));
}
@@ -345,6 +392,16 @@ public class UserDao {
log.info("User status updated to {} for user ID: {}", statusReq, userId);
return convertUserEntityToUserResponse(userEntity);
}
public List<UserResponseBean> getUserByHubId(String hubId) {
// log.info("Fetching users for hub ID: {}", hubId);
// List<UserHubEntity> userHubMappings = userHubRepository.findByHubId(hubId);
List<UserResponseBean> userResponseBeans = new ArrayList<>();
// for (UserHubEntity mapping : userHubMappings) {
// UserEntity userEntity = validateUser(mapping.getUserId());
// userResponseBeans.add(convertUserEntityToUserResponse(userEntity));
// }
return userResponseBeans;
}
public JWTToken validateExistingUserToken(String token) {
return authService.validateExistingUserToken(token);
@@ -354,4 +411,23 @@ public class UserDao {
return authService.validateNewUserToken(token);
}
public List<UserResponseBean> getAllUsers(UserEntity user, Long roleId) {
List<UserEntity> users;
if (roleId != null) {
log.info("Fetching users by role ID: {}", roleId);
RoleEntity roleEntity=roleService.validateRole(roleId);
users = userRepository.findByRoleEntityIdAndHubId(roleEntity.getId(), user.getHub().getId());
} else {
log.info("Fetching all users");
users = userRepository.findByHubId(user.getHub().getId());
}
List<UserResponseBean> userResponseBeans = users.stream()
.map(this::convertUserEntityToUserResponse)
.collect(Collectors.toList());
log.info("Total users found with role ID {}: {}", roleId, userResponseBeans.size());
return userResponseBeans;
}
}

View File

@@ -39,4 +39,7 @@ public class ApplicationEntity extends BaseEntity {
@OneToOne
@JoinColumn(name = "PROTOCOL_NUMBER")
private ProtocolEntity protocol;
@Column(name = "HUB_ID")
private Long hubId;
}

View File

@@ -0,0 +1,35 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDateTime;
@Entity
@Data
@Table(name = "assigned_applications")
public class AssignedApplicationsEntity extends BaseEntity{
@ManyToOne
@JoinColumn(name = "APPLICATION_ID")
private ApplicationEntity application;
@Column(name = "USER_ID")
private Long userId;
@Column(name = "ASSIGNED_BY")
private Long assignedBy;
@Column(name = "STATUS")
private String status;
@Column(name = "NOTE")
private String note;
@Column(name="IS_DELETED")
private Boolean isDeleted=false;
@Column(nullable = false)
private LocalDateTime assignedAt;
}

View File

@@ -61,4 +61,7 @@ public class BeneficiaryEntity extends BaseEntity {
@Column(name = "EMAIL_PEC")
private String emailPec;
@Column(name = "HUB_ID")
private Long hubId;
}

View File

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

View File

@@ -4,6 +4,8 @@ import java.math.BigDecimal;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Data;
@@ -56,4 +58,9 @@ public class CompanyEntity extends BaseEntity{
@Column(name = "CONTACT_EMAIL")
private String contactEmail;
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
}

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

@@ -0,0 +1,44 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Entity
@Table(name = "LOGIN_ATTEMPT")
@Getter
@Setter
public class LoginAttemptEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true)
private Long id;
@Column(name = "USERNAME")
private String username;
@Column(name = "USER_ID")
private Long userId;
@Column(name = "ATTEMPT_DATE", nullable = false)
private LocalDateTime attemptDate;
@Column(name = "IP_ADDRESS", length = 100)
private String ipAddress;
@Column(name = "USER_AGENT")
private String userAgent;
@Column(name = "RESULT", length = 100, nullable = false)
private String result;
@Column(name = "ERROR_MSG")
private String errorMsg;
@Column(name = "ATTEMPT_TYPE", length = 100, nullable = false)
private String type;
}

View File

@@ -25,4 +25,7 @@ public class ProtocolEntity extends BaseEntity {
@Column(name="APPLICATION_ID")
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")
private String authenticationObject;
@Column(name = "IN_RESPONSE_TO")
private String inResponseTo;
@Column(name = "ISSUE_INSTANT")
private String issueInstant;
@Column(name = "SAML_ID")
private String samlId;
@Column(name = "HUB_UUID")
private String hubUuid;
@Column(name = "STATUS")
private String status;
@Column(name = "TOKEN")
private String token;

View File

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

View File

@@ -22,4 +22,7 @@ public class UserWithCompanyEntity extends BaseEntity{
@Column(name = "IS_LEGAL_REPRESENTANT")
private Boolean isLegalRepresentant;
@Column(name = "IS_DELETED")
private Boolean isDeleted = false;
}

View File

@@ -6,7 +6,10 @@ public enum ApplicationStatusTypeEnum {
DRAFT("DRAFT"),
SUBMIT("SUBMIT"),
DISCARD("DISCARD");
AWAITING("AWAITING"),
READY("READY"),
DISCARD("DISCARD"),
EVALUATION("EVALUATION");
private String value;

View File

@@ -0,0 +1,21 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum AssignedApplicationEnum {
ASSIGNED("ASSIGNED"),
APPROVED("APPROVED"),
REJECTED("REJECTED");
private final String value;
AssignedApplicationEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}

View File

@@ -0,0 +1,25 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum LoginAttemptResultEnum {
SUCCESS("SUCCESS"),
FAILED("FAILED");
private String value;
LoginAttemptResultEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}

View File

@@ -0,0 +1,25 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum LoginAttemptTypeEnum {
LOGIN("LOGIN"),
SWITCH("SWITCH");
private String value;
LoginAttemptTypeEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}

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

@@ -0,0 +1,10 @@
package net.gepafin.tendermanagement.model.request;
import lombok.Data;
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
@Data
public class AssignedApplicationsRequest {
private String note;
private AssignedApplicationEnum status;
}

View File

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

View File

@@ -2,7 +2,6 @@ package net.gepafin.tendermanagement.model.request;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import lombok.Data;

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
public class InitiatePasswordResetReq {
private String email;
private String hubUuid;
}

View File

@@ -0,0 +1,18 @@
package net.gepafin.tendermanagement.model.request;
import lombok.Getter;
import lombok.Setter;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
@Getter
@Setter
public class LoginAttemptReq {
private String userName;
@NotNull
private Long userId;
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,26 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.model.BaseBean;
import java.time.LocalDateTime;
@Data
public class AssignedApplicationsResponse extends BaseBean {
private Long applicationId;
private Long userId;
private Long assignedBy;
private AssignedApplicationEnum status;
private String note;
private LocalDateTime assignedAt;
private Long protocolNumber;
private String callName;
private String beneficiaryName;
private LocalDateTime submissionDate;
private LocalDateTime callStartDate;
private LocalDateTime callEndDate;
}

View File

@@ -5,8 +5,10 @@ import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import net.gepafin.tendermanagement.util.DynamicLocalTimeSerializer;
@Data
public class CallResponse {
@@ -47,8 +49,10 @@ public class CallResponse {
private String phoneNumber;
@JsonSerialize(using = DynamicLocalTimeSerializer.class)
private LocalTime startTime;
@JsonSerialize(using = DynamicLocalTimeSerializer.class)
private LocalTime endTime;
private LocalDateTime createdDate;

View File

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

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,38 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Getter;
import lombok.Setter;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import java.io.Serializable;
@Getter
@Setter
public class LoginAttemptPageableResponseBean<T> implements Serializable {
private transient T body;
private Long totalRecords;
private int currentPage;
private int totalPages;
private int pageSize;
private Status status;
private String message;
}

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

@@ -32,12 +32,13 @@ public interface ApplicationRepository extends JpaRepository<ApplicationEntity,
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.userId = :userId AND a.company.id = :companyId AND a.status = 'SUBMIT' ")
Long countSubmittedApplicationsByUserId(@Param("userId") Long userId, @Param("companyId") Long companyId);
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'SUBMIT'")
Long countSubmittedApplications();
List<ApplicationEntity> findByCompanyIdAndUserIdAndIsDeletedFalse(Long companyId,Long userId);
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'DRAFT'")
Long countDraftApplications();
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'SUBMIT' And a.hubId = :hubId")
public Long countSubmittedApplicationsByHubId(@Param("hubId") Long hubId);
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'DRAFT' And a.hubId = :hubId")
public Long countDraftApplicationsByHubId(@Param("hubId") Long hubId);
}

View File

@@ -0,0 +1,13 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface AssignedApplicationsRepository extends JpaRepository<AssignedApplicationsEntity,Long>, JpaSpecificationExecutor<AssignedApplicationsEntity>{
Optional<AssignedApplicationsEntity> findByApplicationIdAndIsDeletedFalse(Long applicationId);
Optional<AssignedApplicationsEntity> findByIdAndIsDeletedFalse(Long id);
}

View File

@@ -1,8 +1,8 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
@@ -11,18 +11,30 @@ import java.util.List;
@Repository
public interface CallRepository extends JpaRepository<CallEntity, Long> {
public CallEntity findByIdAndStatusNotIn(Long id, List<String> status);
List<CallEntity> findByStatusIn(List<String> callStatus);
// public CallEntity findByIdAndStatusNotIn(Long id, List<String> status);
public CallEntity findByIdAndStatus(Long id,String status);
// List<CallEntity> findByStatusIn(List<String> callStatus);
public Long countByStatus(String status);
// public CallEntity findByIdAndStatus(Long id,String status);
@Query("SELECT COALESCE(SUM(c.amount), 0) FROM CallEntity c WHERE c.status = 'PUBLISH'")
BigDecimal findTotalAmountOfPublishedCalls();
// public Long countByStatus(String status);
@Query("SELECT c.name, COUNT(a.id) " +
"FROM CallEntity c LEFT JOIN ApplicationEntity a ON c.id = a.call.id " +
"GROUP BY c.name")
List<Object[]> findApplicationsPerCall();
// @Query("SELECT COALESCE(SUM(c.amount), 0) FROM CallEntity c WHERE c.status = 'PUBLISH'")
// BigDecimal findTotalAmountOfPublishedCalls();
// @Query("SELECT c.name, COUNT(a.id) " +
// "FROM CallEntity c LEFT JOIN ApplicationEntity a ON c.id = a.call.id " +
// "GROUP BY c.name")
// List<Object[]> findApplicationsPerCall();
public List<CallEntity> findByStatusInAndHubId(List<String> callStatus, Long hubId);
public CallEntity findByIdAndStatusAndHubId(Long id, String status, Long hubId);
public Long countByStatusAndHubId(String status, Long hubId);
public CallEntity findByIdAndStatusNotInAndHubId(Long id, List<String> status, Long hubId);
@Query("SELECT COALESCE(SUM(c.amount), 0) FROM CallEntity c WHERE c.status = 'PUBLISH' And c.hub.id = :hubId")
BigDecimal findTotalAmountOfPublishedCallsAndHubId(@Param("hubId") Long hubId);
}

View File

@@ -4,6 +4,7 @@ import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import net.gepafin.tendermanagement.entities.CompanyEntity;
@@ -11,13 +12,14 @@ import net.gepafin.tendermanagement.entities.CompanyEntity;
@Repository
public interface CompanyRepository extends JpaRepository<CompanyEntity, Long> {
List<CompanyEntity> findByIdIn(List<Long> companyIds);
List<CompanyEntity> findByIdInAndHubId(List<Long> companyIds, Long hubId);
Boolean existsByVatNumber(String vatNumber);
CompanyEntity findByVatNumber(String vatNumber);
Boolean existsByVatNumberAndHubId(String vatNumber, Long hubId);
@Query("SELECT COUNT(c) FROM CompanyEntity c")
long countTotalCompanies();
@Query("SELECT COUNT(c) FROM CompanyEntity c where c.hub.id = :hubId")
long countTotalCompaniesByHubId(@Param("hubId") Long hubId);
CompanyEntity findByVatNumberAndHubId(String vatNumber, Long hubId);
}

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

@@ -19,5 +19,6 @@ public interface FaqRepository extends JpaRepository<FaqEntity, Long> {
List<FaqEntity> findByCallIdAndIsDeletedFalse(Long callId);
Optional<FaqEntity> findByIdAndCallIdAndIsDeletedFalse(Long id, Long callId);
List<FaqEntity> findByCompanyIdAndUserIdAndIsDeletedFalse(Long companyId,Long userId);
}

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

@@ -0,0 +1,19 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface LoginAttemptRepository extends JpaRepository<LoginAttemptEntity,Long> {
@Query("SELECT la FROM LoginAttemptEntity la LEFT JOIN UserEntity u ON u.email = la.username WHERE u.hub.id = :hubId")
Page<LoginAttemptEntity> findByHubId(@Param("hubId") Long hubId, PageRequest pageRequest);
}

View File

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

View File

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

View File

@@ -4,22 +4,25 @@ import net.gepafin.tendermanagement.entities.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByEmailIgnoreCase(String email);
boolean existsByEmailIgnoreCase(String email);
UserEntity findByEmail(String email);
Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale);
boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale);
UserEntity findByBeneficiaryId(Long beneficiaryId);
Long countByStatusAndRoleEntity_RoleType(String status, String roleName);
Optional<UserEntity> findByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
boolean existsByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
List<UserEntity> findByRoleEntityIdAndHubId(Long roleId, Long hubId);
List<UserEntity> findByHubId(Long hubId);
Long countByStatusAndRoleEntityRoleTypeAndHubId(String status, String roleName, Long hubId);
Optional<UserEntity> findByBeneficiaryCodiceFiscaleAndHubId(String codiceFiscale, Long hubId);
boolean existsByBeneficiaryCodiceFiscaleAndHubId(String codiceFiscale, Long hubId);
}

View File

@@ -12,11 +12,11 @@ import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
public interface UserWithCompanyRepository extends JpaRepository<UserWithCompanyEntity, Long> {
void deleteByCompanyId(Long companyId);
void deleteByCompanyIdAndIsDeletedFalse(Long companyId);
@Query("SELECT uwc.companyId FROM UserWithCompanyEntity uwc WHERE uwc.userId = :userId")
List<Long> findCompanyIdByUserId(@Param("userId") Long userId);
@Query("SELECT u.companyId FROM UserWithCompanyEntity u WHERE u.userId = :userId AND u.isDeleted = false")
List<Long> findActiveCompanyIdsByUserId(@Param("userId") Long userId);
Optional<UserWithCompanyEntity> findByUserIdAndCompanyId(Long userId, Long companyId);
Optional<UserWithCompanyEntity> findByUserIdAndCompanyIdAndIsDeletedFalse(Long userId, Long companyId);
}

View File

@@ -22,7 +22,7 @@ public interface ApplicationService {
ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId);
List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId, Long companyId);
List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId, Long companyId,String status);
void deleteApplication(HttpServletRequest request, Long applicationId);
@@ -40,4 +40,6 @@ public interface ApplicationService {
public void deleteSignedDocument(HttpServletRequest request, Long applicationId);
public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId);
}

View File

@@ -0,0 +1,19 @@
package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import java.util.List;
public interface AssignedApplicationsService {
AssignedApplicationsResponse createAssignedApplications(
HttpServletRequest request, Long applicationId, Long userId, AssignedApplicationsRequest assignedApplicationsRequest);
void deleteApplication(HttpServletRequest request, Long id);
List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId);
AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, AssignedApplicationsRequest assignedApplicationsRequest);
AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id);
}

View File

@@ -19,18 +19,16 @@ public interface CallService {
CallResponse updateCallStep1(HttpServletRequest request, Long callId, UpdateCallRequestStep1 updateCallRequest);
CallResponse getCallById (Long callId);
CallResponse getCallById (HttpServletRequest request, Long callId);
List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request);
CallResponse validateCallData(Long callId);
CallEntity getCallEntityById(Long id);
CallResponse validateCallData(HttpServletRequest request, Long callId);
CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq);
CallEntity validateCall(Long callId);
CallEntity validatePublishedCall(Long callId);
byte[] downloadCallDocumentsAsZip(Long callId);
CallEntity validatePublishedCall(Long callId, Long hubId);
byte[] downloadCallDocumentsAsZip(HttpServletRequest request, Long callId);
}

View File

@@ -40,6 +40,7 @@ public interface CompanyService {
void deleteCompanyDelegation(HttpServletRequest request, Long companyId);
UserWithCompanyEntity getUserWithCompanyEntity(Long userId,Long companyId);
void removeCompanyFromList(HttpServletRequest request, Long companyId);
}

View File

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

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

@@ -0,0 +1,15 @@
package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
import net.gepafin.tendermanagement.model.request.LoginAttemptReq;
import net.gepafin.tendermanagement.model.response.LoginAttemptPageableResponseBean;
import java.util.List;
public interface LoginAttemptService {
LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(HttpServletRequest request, Integer pageNo, Integer pageLimit);
void createLoginAttempt(LoginAttemptReq loginAttemptReq, HttpServletRequest request);
}

View File

@@ -1,5 +1,6 @@
package net.gepafin.tendermanagement.service;
import net.gepafin.tendermanagement.entities.RoleEntity;
import net.gepafin.tendermanagement.model.request.RoleReq;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
@@ -15,4 +16,5 @@ public interface RoleService {
void deleteRole(Long roleId);
List<RoleResponseBean> getAllRoles();
RoleEntity validateRole(Long roleId);
}

View File

@@ -12,16 +12,18 @@ import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.util.JWTToken;
import java.util.List;
public interface UserService {
JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq);
UserResponseBean updateUser(Long userId, UpdateUserReq userReq);
UserResponseBean updateUser(HttpServletRequest request, Long userId, UpdateUserReq userReq);
UserResponseBean getUserById(Long userId);
UserResponseBean getUserById(HttpServletRequest request, Long userId);
void deleteUser(Long userId);
void deleteUser(HttpServletRequest request, Long userId);
JWTToken login(LoginReq loginReq);
JWTToken login(LoginReq loginReq,HttpServletRequest request);
UserEntity validateUser(Long userId);
@@ -29,7 +31,7 @@ public interface UserService {
Boolean resetPassword(ResetPasswordReq resetPasswordReq);
Boolean changePassword(ChangePasswordRequest request);
Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request);
void logoutUser(HttpServletRequest request, HttpServletResponse response);
@@ -41,4 +43,8 @@ public interface UserService {
UserSamlResponse validateNewUserToken(HttpServletRequest request, String token);
UserEntity getUserByBeneficiaryId(Long beneficiaryId);
public UserEntity getUserEntityById(Long userId);
List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId);
}

View File

@@ -40,21 +40,19 @@ public class ApplicationServiceImpl implements ApplicationService {
@Transactional(rollbackFor = Exception.class)
public ApplicationResponseBean createApplication(HttpServletRequest request,
ApplicationRequestBean applicationRequestBean, Long applicationId, Long formId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.createApplication(applicationRequestBean, userEntity, formId, applicationId);
return applicationDao.createApplication(request, applicationRequestBean, formId, applicationId);
}
@Override
@Transactional(readOnly = true)
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.getApplicationByFormId(applicationId,formId,userEntity);
return applicationDao.getApplicationByFormId(request, applicationId,formId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteApplication(HttpServletRequest request, Long applicationId) {
applicationDao.deleteById(applicationId);
applicationDao.deleteById(request, applicationId);
}
@Override
@@ -67,6 +65,7 @@ public class ApplicationServiceImpl implements ApplicationService {
public ApplicationResponse createApplication(HttpServletRequest request, Long companyId, ApplicationRequest applicationRequest, Long callId) {
UserEntity userEntity = validator.validateUser(request);
CompanyEntity companyEntity = validator.validateUserWithCompany(request, companyId);
validator.validateUserWithCall(userEntity, callId);
return applicationDao.createApplicationByCallId(companyEntity, applicationRequest, callId, userEntity);
}
@@ -74,25 +73,25 @@ public class ApplicationServiceImpl implements ApplicationService {
public NextOrPreviousFormResponse getNextOrPreviousForm(HttpServletRequest request, Long applicationId, Long formId,
FormActionEnum action) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
return flowFormDao.getNextOrPreviousForm(applicationEntity, formId, action);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.updateApplicationStatus(userEntity, applicationId, status);
return applicationDao.updateApplicationStatus(request, applicationId, status);
}
@Override
@Transactional(readOnly = true)
public List<ApplicationResponse> getAllApplications(HttpServletRequest request, Long callId, Long companyId) {
public List<ApplicationResponse> getAllApplications(HttpServletRequest request, Long callId, Long companyId , String status) {
UserEntity userEntity = validator.validateUser(request);
if (companyId != null) {
validator.validateUserWithCompany(request, companyId);
}
return applicationDao.getAllApplications(userEntity, callId, companyId);
return applicationDao.getAllApplications(userEntity, callId, companyId , status);
}
@Override
@Transactional(rollbackFor = Exception.class)
@@ -112,4 +111,11 @@ public class ApplicationServiceImpl implements ApplicationService {
applicationDao.deleteSignedDocument(request, applicationId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId) {
return applicationDao.validateApplication(request, applicationId);
}
}

View File

@@ -0,0 +1,57 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.AssignedApplicationsDao;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.service.AssignedApplicationsService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class AssignedApplicationsServiceImpl implements AssignedApplicationsService {
@Autowired
private Validator validator;
@Autowired
private AssignedApplicationsDao assignedApplicationsDao;
@Override
@Transactional(rollbackFor = Exception.class)
public AssignedApplicationsResponse createAssignedApplications(HttpServletRequest request, Long applicationId, Long userId, AssignedApplicationsRequest assignedApplicationsRequest) {
UserEntity assignedByUser= validator.validateUser(request);
validator.validatePreInstructor(request, userId);
return assignedApplicationsDao.createAssignedApplications(applicationId,userId,assignedByUser, assignedApplicationsRequest);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteApplication(HttpServletRequest request, Long id) {
assignedApplicationsDao.deleteById(request, id);
}
@Override
@Transactional(readOnly = true)
public List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId) {
return assignedApplicationsDao.getAllAssignedApplications(request, userId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, AssignedApplicationsRequest updatedAssignedApplicationRequest) {
return assignedApplicationsDao.updateAssignedApplication(request, id, updatedAssignedApplicationRequest);
}
@Override
@Transactional(readOnly = true)
public AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id) {
return assignedApplicationsDao.getAssignedApplicationById(request, id);
}
}

View File

@@ -6,9 +6,14 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.CompanyDao;
import net.gepafin.tendermanagement.dao.LoginAttemptDao;
import net.gepafin.tendermanagement.dao.RoleDao;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.LoginAttemptResultEnum;
import net.gepafin.tendermanagement.enums.LoginAttemptTypeEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.LoginReq;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
@@ -18,6 +23,7 @@ import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
@@ -57,29 +63,61 @@ public class AuthenticationService {
@Autowired
private SamlResponseRepository samlResponseLogRepository;
@Autowired
private LoginAttemptDao loginAttemptDao;
@Autowired
private HubService hubService;
@Autowired
public AuthenticationService(TokenProvider tokenProvider, AuthenticationManager authenticationManager) {
this.tokenProvider = tokenProvider;
this.authenticationManager = authenticationManager;
}
public JWTToken login(LoginReq loginReq) {
public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
UserEntity user=null;
LoginAttemptEntity loginAttemptEntity = prepareLoginAttemptEntity(loginReq, request);
log.info("Attempting login for email: {}", loginReq.getEmail());
String emailWithHubId = loginReq.getEmail()+":"+loginReq.getHubUuid();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
loginReq.getEmail(), loginReq.getPassword());
emailWithHubId, loginReq.getPassword());
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
log.info("Authentication successful for email: {}", loginReq.getEmail());
UserEntity user = userRepository.findByEmailIgnoreCase(loginReq.getEmail())
user = userRepository.findByEmailIgnoreCaseAndHubUniqueUuid(loginReq.getEmail(), loginReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
loginAttemptEntity.setUserId(user.getId());
if (Boolean.FALSE.equals(UserStatusEnum.ACTIVE.getValue().equals(user.getStatus()))) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
createSuccessLoginAttempt(loginAttemptEntity);
return getJWTTokenBean(user, loginReq.getRememberMe());
}
private LoginAttemptEntity prepareLoginAttemptEntity(LoginReq loginUserReq, HttpServletRequest request) {
String ipAddress = Utils.getClientIpAddress(request);
String userAgent = request.getHeader("user-agent");
LoginAttemptEntity loginAttemptEntity = new LoginAttemptEntity();
loginAttemptEntity.setType(LoginAttemptTypeEnum.LOGIN.getValue());
loginAttemptEntity.setUsername(loginUserReq.getEmail());
loginAttemptEntity.setIpAddress(ipAddress);
loginAttemptEntity.setUserAgent(userAgent);
return loginAttemptEntity;
}
private void createSuccessLoginAttempt(LoginAttemptEntity loginAttemptEntity) {
loginAttemptEntity.setResult(LoginAttemptResultEnum.SUCCESS.getValue());
loginAttemptDao.createLoginAttempt(loginAttemptEntity);
}
private void createFailedLoginAttempt(LoginAttemptEntity loginAttemptEntity, String errorMsg) {
loginAttemptEntity.setResult(LoginAttemptResultEnum.FAILED.getValue());
loginAttemptEntity.setErrorMsg(errorMsg);
loginAttemptDao.createLoginAttempt(loginAttemptEntity);
}
public JWTToken getJWTTokenBean(UserEntity user, Boolean rememberMe) {
user.setLastLogin(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
userRepository.save(user);
@@ -153,10 +191,11 @@ public class AuthenticationService {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
Map<String, List<Object>> userAttributes = Utils
.convertStringIntoMap(samlResponseLogEntity.getAuthenticationObject());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf)
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscaleAndHubId(cf, hub.getId())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
//samlResponseLogRepository.delete(samlResponseLogEntity);
@@ -172,10 +211,11 @@ public class AuthenticationService {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
Map<String, List<Object>> userAttributes = Utils
.convertStringIntoMap(samlResponseLogEntity.getAuthenticationObject());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
if (userRepository.existsByBeneficiaryCodiceFiscale(cf)) {
if (userRepository.existsByBeneficiaryCodiceFiscaleAndHubId(cf, hub.getId())) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_ALREADY_EXIST_MSG));
}

View File

@@ -9,7 +9,6 @@ import net.gepafin.tendermanagement.enums.BeneficiaryCallStatus;
import net.gepafin.tendermanagement.model.request.BeneficiaryPreferredCallReq;
import net.gepafin.tendermanagement.model.response.BeneficiaryPreferredCallResponseBean;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.BeneficiaryPreferredCallService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.Validator;
@@ -17,7 +16,6 @@ import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationExceptio
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.List;
@@ -26,10 +24,10 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
@Autowired
private BeneficiaryPreferredCallDao beneficiaryPreferredCallDao;
@Autowired
private Validator validator;
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@@ -37,22 +35,22 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
@Override
public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(HttpServletRequest request, BeneficiaryPreferredCallReq beneficiaryPreferredCallRequest) {
UserEntity userEntity = validator.validateUser(request);
return beneficiaryPreferredCallDao.createBeneficiaryPreferredCall(beneficiaryPreferredCallRequest,userEntity);
return beneficiaryPreferredCallDao.createBeneficiaryPreferredCall(request, beneficiaryPreferredCallRequest,userEntity);
}
@Override
public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(HttpServletRequest request, Long id) {
return beneficiaryPreferredCallDao.getBeneficiaryPreferredCallById(id);
return beneficiaryPreferredCallDao.getBeneficiaryPreferredCallById(request, id);
}
@Override
public void deleteBeneficiaryPreferredCall(HttpServletRequest request, Long id) {
beneficiaryPreferredCallDao.deleteBeneficiaryPreferredCallById(id);
beneficiaryPreferredCallDao.deleteBeneficiaryPreferredCallById(request, id);
}
@Override
public List<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls(HttpServletRequest request) {
return beneficiaryPreferredCallDao.getAllBeneficiaryPreferredCalls();
return beneficiaryPreferredCallDao.getAllBeneficiaryPreferredCalls(request);
}
// @Override
@@ -68,6 +66,7 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
@Override
public List<BeneficiaryPreferredCallResponseBean> getBeneficiaryPreferredCallByUserId(HttpServletRequest request,Long userId,Long beneficiaryId,Long companyId) {
UserEntity userEntity =validateGetBeneficiaryPreferredCallrequest(request,userId,beneficiaryId);
validator.validateUserId(request, userEntity.getId());
return beneficiaryPreferredCallDao.getBeneficiaryPreferredCallByUserId(userEntity,companyId);
}

View File

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

View File

@@ -49,6 +49,7 @@ public class CompanyServiceImpl implements CompanyService {
@Transactional(rollbackFor = Exception.class)
public CompanyResponse updateCompany(HttpServletRequest request, Long companyId, CompanyRequest companyRequest) {
UserEntity userEntity =validator.validateUser(request);
validator.validateUserWithCompany(request, companyId);
return companyDao.updateCompany(userEntity, companyId, companyRequest);
}
@@ -56,6 +57,7 @@ public class CompanyServiceImpl implements CompanyService {
@Transactional(readOnly = true)
public CompanyResponse getCompany(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
validator.validateUserWithCompany(request, companyId);
return companyDao.getCompany(userEntity, companyId);
}
@@ -63,13 +65,14 @@ public class CompanyServiceImpl implements CompanyService {
@Transactional(rollbackFor = Exception.class)
public void deleteCompany(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
validator.validateUserWithCompany(request, companyId);
companyDao.deleteCompany(userEntity, companyId);
}
@Override
@Transactional(readOnly = true)
public List<CompanyResponse> getCompanyByUserId(HttpServletRequest request, Long userId) {
validator.validateUser(request);
validator.validateUserId(request, userId);
return companyDao.getCompanyByUserId(userId);
}
@@ -91,8 +94,7 @@ public class CompanyServiceImpl implements CompanyService {
@Override
@Transactional(readOnly = true)
public ByteArrayOutputStream downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
UserEntity userEntity =validator.validateUser(request);
return delegationDao.downloadCompanyDelegation(userEntity, companyId, companyDelegationRequest);
return delegationDao.downloadCompanyDelegation(request, companyId, companyDelegationRequest);
}
@Override
@@ -118,4 +120,10 @@ public class CompanyServiceImpl implements CompanyService {
public UserWithCompanyEntity getUserWithCompanyEntity(Long userId,Long companyId){
return companyDao.getUserWithCompany(userId,companyId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeCompanyFromList(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
companyDao.removeCompanyFromList(userEntity, companyId);
}
}

View File

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

View File

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

View File

@@ -5,6 +5,8 @@ import net.gepafin.tendermanagement.dao.FlowDao;
import net.gepafin.tendermanagement.model.request.FlowRequestBean;
import net.gepafin.tendermanagement.model.response.FlowResponseBean;
import net.gepafin.tendermanagement.service.FlowService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -15,15 +17,20 @@ public class FlowServiceImpl implements FlowService {
@Autowired
private FlowDao flowDao;
@Autowired
private Validator validator;
@Override
@Transactional(rollbackFor = Exception.class)
public FlowResponseBean createOrUpdateFlow(HttpServletRequest httpServletRequest, FlowRequestBean flowRequestBean, Long callId) {
validator.validateUserWithCall(validator.validateUser(httpServletRequest), callId);
return flowDao.createOrUpdateFlow(flowRequestBean,callId);
}
@Override
@org.springframework.transaction.annotation.Transactional(readOnly = true)
public FlowResponseBean getFlowByCallId(HttpServletRequest request, Long callId) {
validator.validateUserWithCall(validator.validateUser(request), callId);
return flowDao.getFlowByCallId(callId);
}
}

View File

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

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

@@ -0,0 +1,51 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.LoginAttemptDao;
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.LoginAttemptResultEnum;
import net.gepafin.tendermanagement.enums.LoginAttemptTypeEnum;
import net.gepafin.tendermanagement.model.request.LoginAttemptReq;
import net.gepafin.tendermanagement.model.response.LoginAttemptPageableResponseBean;
import net.gepafin.tendermanagement.service.LoginAttemptService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class LoginAttemptServiceImpl implements LoginAttemptService {
@Autowired
LoginAttemptDao loginAttemptDao;
@Autowired
private Validator validator;
@Override
public LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(HttpServletRequest request, Integer pageNo, Integer pageLimit) {
return loginAttemptDao.getLoginAttemptsList(validator.validateUser(request), pageNo, pageLimit);
}
@Override
public void createLoginAttempt(LoginAttemptReq loginAttemptReq, HttpServletRequest request) {
String ipAddress = Utils.getClientIpAddress(request);
String userAgent = request.getHeader("user-agent");
LoginAttemptEntity loginAttemptEntity = new LoginAttemptEntity();
loginAttemptEntity.setType(LoginAttemptTypeEnum.SWITCH.getValue());
loginAttemptEntity.setIpAddress(ipAddress);
loginAttemptEntity.setUserAgent(userAgent);
loginAttemptEntity.setUsername(loginAttemptReq.getUserName());
loginAttemptEntity.setResult(LoginAttemptResultEnum.SUCCESS.getValue());
if(loginAttemptReq.getUserId() != null) {
UserEntity userEntity = validator.validateUserId(request, loginAttemptReq.getUserId());
loginAttemptEntity.setUserId(userEntity.getId());
}
loginAttemptDao.createLoginAttempt(loginAttemptEntity);
}
}

View File

@@ -3,6 +3,7 @@ package net.gepafin.tendermanagement.service.impl;
import java.util.List;
import net.gepafin.tendermanagement.dao.RoleDao;
import net.gepafin.tendermanagement.entities.RoleEntity;
import net.gepafin.tendermanagement.model.request.RoleReq;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
import net.gepafin.tendermanagement.service.RoleService;
@@ -46,4 +47,10 @@ public class RoleServiceImpl implements RoleService {
return roleDao.getAllRoles();
}
@Override
@Transactional(readOnly = true)
public RoleEntity validateRole(Long roleId) {
return roleDao.validateRole(roleId);
}
}

View File

@@ -2,13 +2,11 @@ package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
import net.gepafin.tendermanagement.dao.UserDao;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.LoginReq;
import net.gepafin.tendermanagement.model.request.UpdateUserReq;
import net.gepafin.tendermanagement.model.request.UserReq;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
@@ -21,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@@ -32,42 +31,37 @@ public class UserServiceImpl implements UserService {
@Autowired
private Validator validator;
@Autowired
private SamlSuccessHandler samlSuccessHandler;
@Override
@Transactional(rollbackFor = Exception.class)
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
if (tempToken == null) {
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
}else {
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale());
}
return userDao.createUser(request, tempToken, userReq);
}
@Override
@Transactional(rollbackFor = Exception.class)
public UserResponseBean updateUser(Long userId, UpdateUserReq userReq) {
public UserResponseBean updateUser(HttpServletRequest request, Long userId, UpdateUserReq userReq) {
validator.validateUserId(request, userId);
return userDao.updateUser(userId, userReq);
}
@Override
@Transactional(readOnly = true)
public UserResponseBean getUserById(Long userId) {
public UserResponseBean getUserById(HttpServletRequest request, Long userId) {
validator.validateUserId(request, userId);
return userDao.getUserById(userId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteUser(Long userId) {
public void deleteUser(HttpServletRequest request, Long userId) {
validator.validateUserId(request, userId);
userDao.deleteUser(userId);
}
@Override
public JWTToken login(LoginReq loginReq) {
return userDao.login(loginReq);
public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
return userDao.login(loginReq,request);
}
@@ -86,8 +80,8 @@ public class UserServiceImpl implements UserService {
return userDao.resetPassword(resetPasswordReq);
}
@Override
public Boolean changePassword(ChangePasswordRequest request){
return userDao.changePassword(request);
public Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request){
return userDao.changePassword(validator.validateUser(httpServletRequest), request);
}
@Override
public void logoutUser(HttpServletRequest request, HttpServletResponse response) {
@@ -119,4 +113,15 @@ public class UserServiceImpl implements UserService {
public UserEntity getUserByBeneficiaryId(Long beneficiaryId) {
return userDao.getUserByBeneficiaryId(beneficiaryId);
}
@Override
public UserEntity getUserEntityById(Long userId) {
// Calling DAO Function
return userDao.validateUser(userId);
}
@Override
@Transactional(readOnly = true)
public List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId) {
UserEntity user=validator.validateUser(request);
return userDao.getAllUsers(user, roleId);
}
}

View File

@@ -0,0 +1,26 @@
package net.gepafin.tendermanagement.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class DynamicLocalTimeSerializer extends JsonSerializer<LocalTime> {
private static final DateTimeFormatter HH_MM_FORMAT = DateTimeFormatter.ofPattern("HH:mm");
private static final DateTimeFormatter HH_MM_SS_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");
@Override
public void serialize(LocalTime time, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// Use HH:mm if seconds are 00, otherwise use HH:mm:ss
String formattedTime = (time.getSecond() == 0)
? time.format(HH_MM_FORMAT)
: time.format(HH_MM_SS_FORMAT);
gen.writeString(formattedTime);
}
}

View File

@@ -4,15 +4,13 @@ import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,6 +31,8 @@ import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientNotFoundExcep
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientUnauthorizedException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientValidationException;
import static org.apache.commons.lang3.StringUtils.isEmpty;
public class Utils {
@@ -302,6 +302,14 @@ public class Utils {
private static String replaceNull(String text, String target, String replacement) {
return text.replace(target, replacement != null ? replacement : "");
}
public static String getClientIpAddress(HttpServletRequest request) {
String header = request.getHeader("X-Forwarded-For");
if (org.apache.commons.lang3.StringUtils.isBlank(header)) {
return request.getRemoteAddr();
}
return new StringTokenizer(header, ",").nextToken().trim();
}
public static String replaceSpacesWithUnderscores(String content) {
if (content == null) {
@@ -309,5 +317,57 @@ public class Utils {
}
return content.trim().replace(" ", "_");
}
public static List<Map<String, Object>> convertJsonStringIntoJsonList(String jsonString) {
try {
if(isEmpty(jsonString))
{
return new ArrayList<>();
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
return mapper.readValue(jsonString, List.class);
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
public static String convertToString(Object input) {
if (input == null) {
return "null"; // Return string "null" for null input
}
if (input instanceof String) {
return (String) input; // Return the string directly if input is a string
}
if (input instanceof Collection<?>) {
// Handle collections (List, Set, etc.)
return convertCollectionToString((Collection<?>) input);
}
if (input instanceof Map<?, ?>) {
// Handle maps
return convertMapToString((Map<?, ?>) input);
}
// For other types (like Integer, Boolean, etc.), use toString()
return input.toString();
}
private static String convertCollectionToString(Collection<?> collection) {
try {
return mapper.writeValueAsString(collection); // Convert the collection to a JSON string
} catch (JsonProcessingException e) {
throw new RuntimeException("Error converting collection to string", e);
}
}
private static String convertMapToString(Map<?, ?> map) {
try {
return mapper.writeValueAsString(map); // Convert the map to a JSON string
} catch (JsonProcessingException e) {
throw new RuntimeException("Error converting map to string", e);
}
}
}

View File

@@ -4,9 +4,11 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
@@ -14,11 +16,13 @@ import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import net.gepafin.tendermanagement.web.rest.api.errors.UnauthorizedAccessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Map;
@Component
@@ -33,6 +37,12 @@ public class Validator {
@Autowired
private CompanyService companyService;
@Autowired
private CallService callService;
@Autowired
private Environment environment;
public Map<String, Object> getUserInfoFromToken(HttpServletRequest request) {
return tokenProvider.getUserInfoAndUserIdFromToken(request);
}
@@ -55,6 +65,20 @@ public class Validator {
return false;
}
public Boolean checkIsPreInstructor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
// Check if the user has the ROLE_SUPER_ADMIN authority
for (GrantedAuthority authority : authentication.getAuthorities()) {
if (RoleStatusEnum.ROLE_PRE_INSTRUCTOR.getValue().equals(authority.getAuthority())) {
return true;
}
}
}
return false;
}
public void validateRequest(HttpServletRequest request,RoleStatusEnum role) {
if (RoleStatusEnum.ROLE_SUPER_ADMIN.equals(role) && Boolean.FALSE.equals(checkIsSuperAdmin())) {
throw new UnauthorizedAccessException(Status.UNAUTHORIZED, Translator.toLocale(GepafinConstant.INVALID_REQUEST));
@@ -62,14 +86,25 @@ public class Validator {
}
public CompanyEntity validateUserWithCompany(HttpServletRequest request, Long companyId) {
CompanyEntity companyEntity = companyService.validateCompany(companyId);
validateHubId(request, companyEntity.getHub().getId());
if (checkIsSuperAdmin()) {
return companyService.validateCompany(companyId);
return companyEntity;
}
Map<String, Object> userInfo = tokenProvider.getUserInfoAndUserIdFromToken(request);
companyService.validateUserWithCompny(getUserId(userInfo), companyId);
return companyService.validateCompany(companyId);
}
public void validateHubId(HttpServletRequest request, Long hubId) {
UserEntity user = validateUser(request);
Long hubIdFromHttpRequest = user.getHub().getId();
if (Boolean.FALSE.equals(hubIdFromHttpRequest.equals(hubId))) {
throw new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
}
}
private Long getUserId(Map<String, Object> userInfo) {
return Long.parseLong(userInfo.get("userId").toString());
}
@@ -89,10 +124,15 @@ public class Validator {
public UserEntity validateUserId(HttpServletRequest request, Long userId) {
UserEntity user = validateUser(request);
if(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue()) && Boolean.FALSE.equals(user.getId().equals(userId))) {
throw new ForbiddenAccessException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
UserEntity requestedUser = userService.validateUser(userId);
validateHubId(request, requestedUser.getHub().getId());
if (Boolean.FALSE.equals(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_SUPER_ADMIN.getValue()))
&& Boolean.FALSE.equals(user.getId().equals(userId))) {
throw new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
}
return userService.validateUser(userId);
return requestedUser;
}
private Long getUserIdFromToken(HttpServletRequest request) {
@@ -100,4 +140,32 @@ public class Validator {
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);
}
public UserEntity validatePreInstructor(HttpServletRequest request, Long preInstructorUserId) {
UserEntity preInstructorUser = userService.validateUser(preInstructorUserId);
if (checkIsSuperAdmin()) {
if (preInstructorUserId != null) {
validateHubId(request, preInstructorUser.getHub().getId());
}
return preInstructorUser;
} else if (checkIsPreInstructor()) {
return validateUserId(request, preInstructorUserId);
} else {
throw new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
}
}
}

View File

@@ -71,7 +71,8 @@ public interface ApplicationApi {
@GetMapping(value = "", produces = "application/json")
ResponseEntity<Response<List<ApplicationResponse>>> getAllApplications(HttpServletRequest request,
@Parameter(description = "The call id", required = false) @RequestParam(value = "callId", required = false) Long callId,
@Parameter(description = "The company id", required = false) @RequestParam(value = "companyId", required = false) Long companyId);
@Parameter(description = "The company id", required = false) @RequestParam(value = "companyId", required = false) Long companyId,
@Parameter(description = "Application status" ,required = false) @RequestParam(value = "status",required = false)String status);
@Operation(summary = "Api to delete application",
responses = {
@@ -175,16 +176,29 @@ public interface ApplicationApi {
ResponseEntity<Response<ApplicationSignedDocumentResponse>> getSignedDocument(HttpServletRequest request,
@Parameter(description = "The applicationId id", required = true) @PathVariable("applicationId") Long applicationId);
@Operation(summary = "Api to delete signed document", responses = { @ApiResponse(responseCode = "200", description = "OK"),
// @Operation(summary = "Api to delete signed document", 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) })) })
// @DeleteMapping(value = "{applicationId}/signedDocument", produces = "application/json")
// ResponseEntity<Response<Void>> deleteSignedDocument(HttpServletRequest request,
// @Parameter(description = "The applicationId id", required = true) @PathVariable("applicationId") Long applicationId);
@Operation(summary = "Api to validate application",
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) })) })
@DeleteMapping(value = "{applicationId}/signedDocument", produces = "application/json")
ResponseEntity<Response<Void>> deleteSignedDocument(HttpServletRequest request,
@Parameter(description = "The applicationId id", required = true) @PathVariable("applicationId") Long applicationId);
@PostMapping(value = "/{applicationId}/validate", produces = { "application/json" })
ResponseEntity<Response<ApplicationResponse>> validateApplication(HttpServletRequest request,
@Parameter(description = "The application id", required = true) @PathVariable("applicationId") Long applicationId);
}

View File

@@ -0,0 +1,102 @@
package net.gepafin.tendermanagement.web.rest.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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 jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.model.util.Response;
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
public interface AssignedApplicationsApi {
@Operation(summary = "Api to assign a application to preInstructor",
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) }))
})
@PostMapping(value = "/application/{applicationId}")
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
public ResponseEntity<Response<AssignedApplicationsResponse>> createAssignedApplications(
HttpServletRequest request,
@Parameter(description = "ID of the application", required = true) @PathVariable Long applicationId,
@Parameter(description = "The User ID", required = true) @RequestParam("userId") Long userId,
@Valid @RequestBody AssignedApplicationsRequest assignedApplicationsRequest
);
@Operation(summary = "Api to delete assigned application",
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) })) })
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
ResponseEntity<Response<Void>> deleteAssignedApplication(HttpServletRequest request,
@Parameter(description = "The assigned application id", required = true) @PathVariable("id") Long id);
@Operation(summary = "Api to get all assigned applications",
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 = "", produces = "application/json")
ResponseEntity<Response<List<AssignedApplicationsResponse>>> getAllAssignedApplications(HttpServletRequest request,
@Parameter(description = "The User ID", required = false) @RequestParam(value = "userId",required = false) Long userId);
@Operation(summary = "Api to update assigned application",
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) }))
})
@PutMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
public ResponseEntity<Response<AssignedApplicationsResponse>> updateAssignedApplication(HttpServletRequest request,
@Parameter(description = "The Assigned Application id", required = true) @PathVariable("id") Long id,
@Parameter(description = "Assigned Application request object", required = true) @Valid @RequestBody AssignedApplicationsRequest assignedApplicationsRequest);
@Operation(summary = "Api to get an assigned application 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 = "/{id}", produces = "application/json")
ResponseEntity<Response<AssignedApplicationsResponse>> getAssignedApplicationById(HttpServletRequest request,
@Parameter(description = "The assigned application id", required = true) @PathVariable(value = "id", required = true) Long id);
}

View File

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

View File

@@ -142,5 +142,15 @@ public interface CompanyApi {
@DeleteMapping(value = "{companyId}/delegation", produces = { "application/json" })
ResponseEntity<Response<Void>> deleteCompanyDelegation(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId);
@Operation(summary = "Api to remove a company from user ", 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) })) })
@DeleteMapping(value = "user/{companyId}", produces = { "application/json" })
ResponseEntity<Response<Void>> removeCompanyFromList(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId);
}

View File

@@ -72,7 +72,7 @@ public interface EvaluationCriteriaApi {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) }))
})
@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)
@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

@@ -0,0 +1,60 @@
package net.gepafin.tendermanagement.web.rest.api;
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 jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import io.swagger.annotations.ApiParam;
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
import net.gepafin.tendermanagement.model.request.LoginAttemptReq;
import net.gepafin.tendermanagement.model.response.LoginAttemptPageableResponseBean;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.HttpStatus;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.List;
import java.util.Optional;
@Validated
public interface LoginAttemptApi {
default Optional<NativeWebRequest> getRequest() {
return Optional.empty();
}
@Operation(summary = "Api to get list of login attempts", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@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 = "/login-attempt", produces = {"application/json"})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
default ResponseEntity<LoginAttemptPageableResponseBean<List<LoginAttemptEntity>>> getLoginAttemptsList(HttpServletRequest request,
@ApiParam(value = "page number") @RequestParam(name = "pageNo", required = false) Integer pageNo,
@ApiParam(value = "page limit") @RequestParam(name = "pageLimit", required = false) Integer pageLimit) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@Operation(summary = "Api to create a login attempt", responses = {
@ApiResponse(responseCode = "201", description = "Created"),
@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)}))})
@PostMapping(value = "/login-attempt", consumes = {"application/json"})
default ResponseEntity<Response<Void>> createLoginAttempt(@ApiParam(value = "login attempt request", required = true) @Valid @RequestBody LoginAttemptReq loginAttemptReq, HttpServletRequest request) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
}

View File

@@ -1,35 +0,0 @@
package net.gepafin.tendermanagement.web.rest.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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 jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@Validated
public interface PdfApi {
@Operation(summary = "API to generate PDF for an application",
responses = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(mediaType = "application/pdf")),
@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) }))
})
@PostMapping(value = "/{applicationId}/generate-pdf",
produces = { "application/pdf" })
public ResponseEntity<byte[]> generateApplicationPdf(
HttpServletRequest request,
@Parameter(description = "The application id", required = true)
@PathVariable(value = "applicationId", required = true) Long applicationId);
}

Some files were not shown because too many files have changed in this diff Show More