updated code

This commit is contained in:
harish
2024-10-19 13:10:13 +05:30
174 changed files with 7882 additions and 1012 deletions

View File

@@ -3,30 +3,46 @@ package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum;
import net.gepafin.tendermanagement.enums.ApplicationSignedDocumentStatusEnum;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBean;
import net.gepafin.tendermanagement.model.request.ApplicationRequest;
import net.gepafin.tendermanagement.model.request.ApplicationRequestBean;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.ApplicationFormFieldRepository;
import net.gepafin.tendermanagement.repositories.ApplicationFormRepository;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.AmazonS3Service;
import net.gepafin.tendermanagement.service.CallService;
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.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.MailUtil;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
@@ -56,11 +72,61 @@ public class ApplicationDao {
@Autowired
private CallDao callDao;
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId,Long applicationId) {
@Autowired
private FlowFormDao flowFormDao;
@Autowired
private FlowEdgesRepository flowEdgesRepository;
@Autowired
private FlowDataRepository flowDataRepository;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
@Autowired
private Validator validator;
@Autowired
private CompanyService companyService;
@Autowired
private ProtocolRepository protocolRepository;
@Autowired
private SystemEmailTemplatesService systemEmailTemplatesService;
@Autowired
private MailUtil mailUtil;
@Value("${default_System_Receiver_Email}")
private String defaultSystemReceiverEmail;
@Value("${gepafin_email}")
private String gepafinEmail;
@Value("${rinaldo_email}")
private String rinaldoEmail;
@Value("${carlo_email}")
private String carloEmail;
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
@Value("${aws.s3.url.folder.signed.document}")
private String signedDocumentS3Folder;
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId);
CallEntity call = callService.validatePublishedCall(formEntity.getCall().getId());
// callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId);
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))){
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED));
}
formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity);
@@ -68,18 +134,25 @@ public class ApplicationDao {
createOrUpdateMultipleFormFields(applicationRequestBean.getFormFields(), applicationFormEntity,formEntity);
return getApplicationById(applicationEntity.getId(),formEntity.getId());
}
public void validateDelegation(UserEntity user, CompanyEntity company) {
UserWithCompanyEntity userWithCompany = companyService.getUserWithCompanyEntity(user.getId(), company.getId());
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(user.getId(), company.getId(),
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
if (!userWithCompany.getIsLegalRepresentant() && userCompanyDelegationEntity == null) {
throw new CustomValidationException(Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.USER_NOT_AUTHORIZED_TO_CREATE_APPLICATION));
}
}
public ApplicationFormEntity saveApplicationFormEntity(ApplicationFormEntity applicationFormEntity) {
ApplicationFormEntity applicationFormEntity1 = applicationFormRepository.save(applicationFormEntity);
return applicationFormEntity1;
}
public void validateFormId(FormEntity formEntity, CallEntity callEntity) {
if (Boolean.FALSE.equals(formEntity.getId().equals(callEntity.getInitialForm()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FORM_ID_DOES_NOT_MACTHES));
}
}
public ApplicationFormEntity createApplicationFormEntity(ApplicationEntity application, FormEntity formEntity) {
ApplicationFormEntity applicationFormEntity = new ApplicationFormEntity();
applicationFormEntity.setApplication(application);
@@ -88,9 +161,11 @@ public class ApplicationDao {
return applicationFormEntity;
}
public ApplicationEntity createApplicationEntity(UserEntity user, CallEntity call) {
public ApplicationEntity createApplicationEntity(UserEntity user, CallEntity call, CompanyEntity companyEntity) {
validateDelegation(user,companyEntity);
ApplicationEntity entity = new ApplicationEntity();
entity.setUser(user);
entity.setUserId(user.getId());
entity.setCompany(companyEntity);
entity.setCall(call);
entity.setIsDeleted(false);
entity.setStatus(ApplicationStatusTypeEnum.DRAFT.getValue());
@@ -103,7 +178,6 @@ public class ApplicationDao {
ApplicationEntity applicationEntity = validateApplication(id);
ApplicationFormEntity applicationFormEntity = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(),formId);
List<ApplicationFormFieldResponseBean> applicationFormFieldResponseBeans=new ArrayList<>();
ApplicationFormFieldResponseBean applicationFormFieldResponseBeans1=null;
List<ApplicationFormFieldEntity> applicationFormFieldEntities = applicationFormFieldRepository.findByApplicationFormId(applicationFormEntity.getId());
applicationFormFieldResponseBeans=createApplicationFormFieldResponse(applicationFormFieldEntities, applicationFormEntity, applicationFormFieldResponseBeans);
ApplicationResponseBean applicationResponseBean= convertApplicationEntityToApplicationResponseBean(applicationEntity);
@@ -164,58 +238,102 @@ public class ApplicationDao {
log.info("Application deleted with ID: {}", id);
}
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId) {
RoleStatusEnum roleStatus = RoleStatusEnum.valueOf(userEntity.getRoleEntity().getRoleType());
boolean isBeneficiary = RoleStatusEnum.ROLE_BENEFICIARY.equals(roleStatus);
log.info("Fetching applications for RoleType: {}", roleStatus);
List<ApplicationResponse> applicationResponses = new ArrayList<>();
// public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, CompanyEntity companyEntity) {
// boolean isBeneficiary = validator.checkIsBeneficiary();
//
// log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
// List<ApplicationResponse> applicationResponses = new ArrayList<>();
//
// if (callId != null) {
// // Fetch based on callId and user if role is BENEFICIARY, otherwise fetch all for the call
// log.info("Fetching applications for callId: {}", callId);
// CallEntity call = callService.validateCall(callId);
//
// // Use a single method to handle both conditions for consistency
// List<ApplicationEntity> applicationEntities = isBeneficiary
// ? applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(), call.getId())
// .map(List::of) // Convert Optional<ApplicationEntity> to a List of one element
// .orElse(List.of()) // If not present, return an empty list
// : applicationRepository.findByCallIdAndIsDeletedFalse(call.getId());
//
// applicationResponses = applicationEntities.stream()
// .map(this::getApplicationResponse)
// .collect(Collectors.toList());
//
// } else {
// // Fetch all applications for the user if BENEFICIARY, or fetch all applications in general
// List<ApplicationEntity> applicationEntities = isBeneficiary
// ? applicationRepository.findByUserIdAndIsDeletedFalse(companyEntity.getId())
// : applicationRepository.findByIsDeletedFalse();
//
// applicationResponses = applicationEntities.stream()
// .map(this::getApplicationResponse)
// .collect(Collectors.toList());
// }
//
// return applicationResponses;
// }
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId) {
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
if (callId != null) {
// Fetch based on callId and user if role is BENEFICIARY, otherwise fetch all for the call
log.info("Fetching applications for callId: {}", callId);
CallEntity call = callService.validateCall(callId);
Specification<ApplicationEntity> spec = search(userEntity.getId(), callId, companyId);
// Use a single method to handle both conditions for consistency
List<ApplicationEntity> applicationEntities = isBeneficiary
? applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(), call.getId())
.map(List::of) // Convert Optional<ApplicationEntity> to a List of one element
.orElse(List.of()) // If not present, return an empty list
: applicationRepository.findByCallIdAndIsDeletedFalse(call.getId());
List<ApplicationEntity> applicationEntities = applicationRepository.findAll(spec);
applicationResponses = applicationEntities.stream()
.map(this::getApplicationResponse)
.collect(Collectors.toList());
} else {
// Fetch all applications for the user if BENEFICIARY, or fetch all applications in general
List<ApplicationEntity> applicationEntities = isBeneficiary
? applicationRepository.findByUserIdAndIsDeletedFalse(userEntity.getId())
: applicationRepository.findByIsDeletedFalse();
applicationResponses = applicationEntities.stream()
.map(this::getApplicationResponse)
.collect(Collectors.toList());
}
return applicationResponses;
return applicationEntities.stream()
.map(this::getApplicationResponse)
.collect(Collectors.toList());
}
private ApplicationResponse getApplicationResponse(ApplicationEntity applicationEntity) {
private Specification<ApplicationEntity> search(Long userId, Long callId, Long companyId) {
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));
}
if (callId != null) {
predicate = builder.and(predicate, builder.equal(root.get("call").get("id"), callId));
}
if (companyId != null) {
predicate = builder.and(predicate, builder.equal(root.get("company").get("id"), companyId));
}
return predicate;
};
}
private ApplicationResponse getApplicationResponse(ApplicationEntity applicationEntity) {
ApplicationResponse responseBean = new ApplicationResponse();
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalFormSteps = flowFormDao.calculateTotalSteps(flowEdgesList);
Long completedSteps= Long.valueOf(flowFormDao.getCompletedSteps(applicationEntity));
Integer progress=calculateProgress(totalFormSteps,completedSteps);
responseBean.setId(applicationEntity.getId());
responseBean.setProgress(progress);
responseBean.setCallTitle(applicationEntity.getCall().getName());
responseBean.setCallEndDate(applicationEntity.getCall().getEndDate());
responseBean.setModifiedDate(applicationEntity.getCall().getUpdatedDate());
responseBean.setCallId(applicationEntity.getCall().getId());
responseBean.setSubmissionDate(applicationEntity.getSubmissionDate());
responseBean.setStatus(applicationEntity.getStatus());
responseBean.setComments(applicationEntity.getComments());
responseBean.setCompanyId(applicationEntity.getCompany().getId());
responseBean.setCompanyName(applicationEntity.getCompany().getCompanyName());
if(applicationEntity.getProtocol() != null) {
responseBean.setProtocolNumber(applicationEntity.getProtocol().getProtocolNumber());
}
return responseBean;
}
public ApplicationEntity validateApplication(Long id) {
ApplicationEntity applicationEntity= applicationRepository.findById(id).orElseThrow(() ->new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
return applicationEntity;
}
public ApplicationEntity validateApplication(Long id) {
ApplicationEntity applicationEntity = applicationRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
return applicationEntity;
}
private ApplicationResponseBean convertApplicationEntityToApplicationResponseBean(ApplicationEntity entity) {
ApplicationResponseBean response = new ApplicationResponseBean();
@@ -226,6 +344,9 @@ public class ApplicationDao {
response.setCallId(entity.getCall().getId());
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
if(entity.getProtocol() != null) {
response.setProtocolNumber(entity.getProtocol().getProtocolNumber());
}
return response;
}
@@ -259,6 +380,9 @@ public class ApplicationDao {
for (ApplicationFormFieldEntity applicationFormFieldEntity1 : applicationFormFieldEntities) {
if (applicationFormFieldEntity1.getFieldId().equals(applicationFormFieldRequestBean.getFieldId())) {
applicationFormFieldEntity = applicationFormFieldEntity1;
if(applicationFormEntity.getForm().getId().equals(applicationFormEntity.getApplication().getCall().getInitialForm())){
validateRequiredFields(applicationFormEntity.getForm(),applicationFormEntity.getApplication(), applicationFormFieldRequestBean.getFieldId());
}
break;
} else {
applicationFormFieldEntity = new ApplicationFormFieldEntity();
@@ -267,7 +391,13 @@ public class ApplicationDao {
}
}
Utils.setIfUpdated(applicationFormFieldEntity::getFieldId, applicationFormFieldEntity::setFieldId, applicationFormFieldRequestBean.getFieldId());
Utils.setIfUpdated(applicationFormFieldEntity::getFieldValue, applicationFormFieldEntity::setFieldValue, applicationFormFieldRequestBean.getFieldValue());
if(applicationFormFieldRequestBean.getFieldValue() !=null ) {
applicationFormFieldEntity.setFieldValue(Utils.convertObjectToJsonString(applicationFormFieldRequestBean.getFieldValue()));
}
if(applicationFormFieldRequestBean.getFieldValue() ==null ) {
applicationFormFieldEntity.setFieldValue(null);
}
return applicationFormFieldRepository.save(applicationFormFieldEntity);
}
@@ -275,10 +405,15 @@ public class ApplicationDao {
List<Long> documentIds=null;
List<ContentResponseBean> contentResponseBeans=Utils.convertJsonStringToList(formEntity.getContent(),ContentResponseBean.class);
for (ContentResponseBean contentResponseBean:contentResponseBeans){
if(Boolean.TRUE.equals(contentResponseBean.getName().equals("fileupload"))){
if(contentResponseBean.getId().equals(applicationFormFieldRequestBean.getFieldId())) {
String documentId = applicationFormFieldRequestBean.getFieldValue();
documentIds = validateDocumentIds(documentId);
if(Boolean.TRUE.equals(contentResponseBean.getName().equals("fileupload"))) {
if (contentResponseBean.getId().equals(applicationFormFieldRequestBean.getFieldId())) {
Object fieldValueObject = applicationFormFieldRequestBean.getFieldValue();
if (fieldValueObject instanceof String) {
// Safely cast the object to a string
String documentId = (String) fieldValueObject;
// Now you can use documentId as needed
documentIds = validateDocumentIds(documentId);
}
}
}
}
@@ -319,7 +454,9 @@ public class ApplicationDao {
ApplicationFormFieldResponseBean applicationFormFieldResponseBean = new ApplicationFormFieldResponseBean();
applicationFormFieldResponseBean.setApplicationFormId(applicationFormId);
applicationFormFieldResponseBean.setFieldId(applicationFormFieldEntity.getFieldId());
applicationFormFieldResponseBean.setFieldValue(applicationFormFieldEntity.getFieldValue());
if(applicationFormFieldEntity.getFieldValue() != null) {
applicationFormFieldResponseBean.setFieldValue(Utils.getFieldValueAsObject(applicationFormFieldEntity.getFieldValue()));
}
applicationFormFieldResponseBean.setId(applicationFormFieldEntity.getId());
applicationFormFieldResponseBean.setCreatedDate(applicationFormFieldEntity.getCreatedDate());
applicationFormFieldResponseBean.setUpdatedDate(applicationFormFieldEntity.getUpdatedDate());
@@ -330,15 +467,19 @@ public class ApplicationDao {
return applicationEntity;
}
public ApplicationGetResponseBean getApplicationByFormId( Long applicationId,Long formId, UserEntity userEntity) {
public ApplicationGetResponseBean getApplicationByFormId( Long applicationId, Long formId, UserEntity userEntity) {
List<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
List<FormEntity> formEntities = new ArrayList<>();
ApplicationEntity applicationEntity = applicationRepository.findById(applicationId)
boolean isBeneficiary = isBeneficiary(userEntity);
ApplicationEntity applicationEntity = isBeneficiary
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)))
: applicationRepository.findById(applicationId)
.stream().findFirst()
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
if (formId != null) {
FormEntity formEntity = formService.validateForm(formId);
Optional<ApplicationEntity> application = applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(),
Optional<ApplicationEntity> application = applicationRepository.findByIdAndUserIdAndCallIdAndIsDeletedFalse(applicationId, userEntity.getId(),
formEntity.getCall().getId());
applicationEntity=application.get();
formEntities.add(formEntity);
@@ -356,6 +497,12 @@ public class ApplicationDao {
return createApplicationGetResponseBean(applicationEntity, formEntities, formApplicationResponses);
}
private boolean isBeneficiary(UserEntity userEntity) {
RoleStatusEnum roleStatus = RoleStatusEnum.valueOf(userEntity.getRoleEntity().getRoleType());
boolean isBeneficiary = RoleStatusEnum.ROLE_BENEFICIARY.equals(roleStatus);
return isBeneficiary;
}
private void addFormApplication(FormEntity formEntity, ApplicationEntity applicationEntity,
List<FormApplicationResponse> formApplicationResponses) {
FormApplicationResponse formApplicationResponse = processForm(formEntity, applicationEntity);
@@ -379,7 +526,7 @@ public class ApplicationDao {
}
private ApplicationGetResponseBean createApplicationGetResponseBean(ApplicationEntity applicationEntity, List<FormEntity> formEntities, List<FormApplicationResponse> formApplicationResponses) {
ApplicationGetResponseBean applicationGetResponseBean =createApplicationGetResponseBean(applicationEntity);
ApplicationGetResponseBean applicationGetResponseBean = createApplicationGetResponseBean(applicationEntity);
applicationGetResponseBean.setForm(formApplicationResponses);
return applicationGetResponseBean;
}
@@ -392,6 +539,11 @@ public class ApplicationDao {
applicationGetResponseBean.setSubmissionDate(applicationEntity.getSubmissionDate());
applicationGetResponseBean.setCallId(applicationEntity.getCall().getId());
applicationGetResponseBean.setCallTitle(applicationEntity.getCall().getName());
applicationGetResponseBean.setCompanyId(applicationEntity.getCompany().getId());
if(applicationEntity.getProtocol() != null) {
applicationGetResponseBean.setProtocolNumber(applicationEntity.getProtocol().getProtocolNumber());
}
applicationGetResponseBean.setCompanyName(applicationEntity.getCompany().getCompanyName());
return applicationGetResponseBean;
}
@@ -404,51 +556,289 @@ public class ApplicationDao {
return formApplicationResponse;
}
public ApplicationResponse createApplicationByCallId(ApplicationRequest applicationRequest,Long callId,UserEntity userEntity){
CallEntity call=callService.validateCall(callId);
call = callService.validatePublishedCall(call.getId());
checkIfApplicationExists(call,userEntity);
ApplicationEntity applicationEntity=createApplicationEntity(userEntity,call);
applicationEntity.setComments(applicationRequest.getComments());
applicationEntity=saveApplicationEntity(applicationEntity);
ApplicationResponse applicationResponse=getApplicationResponse(applicationEntity);
return applicationResponse;
}
public void checkIfApplicationExists(CallEntity call,UserEntity userEntity){
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(),call.getId());
public ApplicationResponse createApplicationByCallId(CompanyEntity companyEntity,
ApplicationRequest applicationRequest, Long callId, UserEntity userEntity) {
CallEntity call = callService.validateCall(callId);
// call = callService.validatePublishedCall(call.getId());
checkIfApplicationExists(call, companyEntity, userEntity);
ApplicationEntity applicationEntity = createApplicationEntity(userEntity, call, companyEntity);
applicationEntity.setComments(applicationRequest.getComments());
applicationEntity = saveApplicationEntity(applicationEntity);
ApplicationResponse applicationResponse = getApplicationResponse(applicationEntity);
return applicationResponse;
}
public void checkIfApplicationExists(CallEntity call, CompanyEntity companyEntity, UserEntity userEntity){
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByUserIdAndCompanyIdAndCallIdAndIsDeletedFalse(userEntity.getId(), companyEntity.getId(),call.getId());
if(applicationEntity.isPresent()){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
}
}
public ApplicationEntity getApplicationByCallAndUser(CallEntity call, UserEntity userEntity) {
return applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(), call.getId())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
}
public void updateApplicationStatus(Long applicationId, ApplicationStatusTypeEnum status) {
public ApplicationResponse updateApplicationStatus(UserEntity userEntity, Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
}
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)) {
CallEntity callEntity = applicationEntity.getCall();
Long initialFormId = callEntity.getInitialForm();
Long finalFormId = callEntity.getFinalForm();
// if (initialFormId == null || finalFormId == null) {
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));
// }
ApplicationFormEntity initialApplicationForm = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), initialFormId);
ApplicationFormEntity finalApplicationForm = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), finalFormId);
if (initialApplicationForm == null || finalApplicationForm == null) {
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));
}
Long maxProtocolNumber=protocolRepository.findMaxProtocolNumber();
Long protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 1;
ProtocolEntity protocolEntity=createProtocolEntity(applicationEntity,protocolNumber);
applicationEntity.setProtocol(protocolEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
} else {
applicationEntity.setStatus(status.getValue());
}
saveApplicationEntity(applicationEntity);
applicationEntity = saveApplicationEntity(applicationEntity);
return getApplicationResponse(applicationEntity);
}
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));
}
if (completedSteps < 0 || completedSteps > totalSteps) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.COMPLETED_STEPS_NOT_VALID));
}
double progress = ((double) completedSteps / totalSteps) * 100;
return (int) Math.round(progress);
}
public void validateFormFields(ApplicationRequestBean request, FormEntity formEntity) {
List<ContentResponseBean> contentResponseBeans=Utils.convertJsonStringToList(formEntity.getContent(),ContentResponseBean.class);
List<ApplicationFormFieldRequestBean> requestFields = request.getFormFields();
Map<String, String> contentMap = contentResponseBeans.stream()
.collect(Collectors.toMap(ContentResponseBean::getId, ContentResponseBean::getLabel)); // Change getLabel() if needed
FieldValidator validator = FieldValidator.create();
for (ApplicationFormFieldRequestBean requestField : requestFields) {
String fieldId = requestField.getFieldId();
if (!contentMap.containsKey(fieldId)) {
validator.addError(MessageFormat.format(Translator.toLocale(GepafinConstant.FIELD_ID_NOT_FOUND), fieldId));
}
}
validator.validate();
}
public void validateRequiredFields(FormEntity formEntity, ApplicationEntity applicationEntity, String fieldId) {
FlowDataEntity flowDataEntity = flowDataRepository.findByFormIdAndCallId(
formEntity.getId(), applicationEntity.getCall().getId());
if (flowDataEntity == null) {
return;
}
ApplicationFormFieldEntity applicationFormFieldEntity = applicationFormFieldRepository
.findByFieldIdAndApplicationFormFormIdAndApplicationFormApplicationId(
flowDataEntity.getChoosenField(), formEntity.getId(), applicationEntity.getId())
.orElse(null);
if (applicationFormFieldEntity == null || !fieldId.equals(applicationFormFieldEntity.getFieldId())) {
return;
}
List<Long> nextFormIds = flowEdgesRepository.findBySourceIdAndCallId(
formEntity.getId(), applicationEntity.getCall().getId())
.stream()
.map(FlowEdgesEntity::getTargetId)
.collect(Collectors.toList());
Optional<Long> nextFormIdOptional = flowDataRepository.findByChoosenValueAndFormIdIn(
applicationFormFieldEntity.getFieldValue(), nextFormIds)
.map(FlowDataEntity::getFormId);
if (nextFormIdOptional.isPresent()) {
Long nextFormId = nextFormIdOptional.get();
FormEntity nextForm = formService.validateForm(nextFormId);
ApplicationFormEntity nextApplicationFormEntity = applicationFormRepository.findByApplicationIdAndFormId(
applicationEntity.getId(), nextForm.getId());
if (nextApplicationFormEntity != null) {
List<ApplicationFormFieldEntity> nextApplicationFormFieldEntities = applicationFormFieldRepository.findByApplicationFormId(nextApplicationFormEntity.getId());
applicationFormFieldRepository.deleteAll(nextApplicationFormFieldEntities);
applicationFormRepository.delete(nextApplicationFormEntity);
}
}
}
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Long protocolNumber){
ProtocolEntity protocolEntity=new ProtocolEntity();
protocolEntity.setCall(applicationEntity.getCall().getId());
LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
protocolEntity.setYear(utcDateTime.getYear());
protocolEntity.setProtocolNumber(protocolNumber);
protocolEntity.setTime(LocalTime.now());
protocolEntity.setApplicationId(applicationEntity.getId());
protocolRepository.save(protocolEntity);
return protocolEntity;
}
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity) {
CallEntity call =applicationEntity.getCall();
CompanyEntity company = applicationEntity.getCompany();
ProtocolEntity protocol = applicationEntity.getProtocol();
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_USER_AND_COMPANY,
call, null);
// Create the map for subject placeholders
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
subjectPlaceholders.put("{{company_name}}", company.getCompanyName());
// Create the map for body placeholders
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{protocol_number}}", protocol.getProtocolNumber().toString());
bodyPlaceholders.put("{{date}}", DateTimeUtil.formatLocalDateTime(protocol.getCreatedDate(), GepafinConstant.DD_MM_YYYY));
bodyPlaceholders.put("{{time}}", DateTimeUtil.parseLocalTimeToString(protocol.getTime(), GepafinConstant.HH_MM_SS));
// Replace placeholders in the subject and body
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
String email = userEntity.getEmail();
if (userEntity.getBeneficiary() != null) {
email = userEntity.getBeneficiary().getEmail();
}
mailUtil.sendByMailGun(subject, body, List.of(email), null);
mailUtil.sendByMailGun(subject, body, List.of(applicationEntity.getCompany().getEmail()), null);
}
private void sendMailTodefaultSystemAndGepafin(UserEntity userEntity, ApplicationEntity applicationEntity) {
CallEntity call = applicationEntity.getCall();
CompanyEntity company = applicationEntity.getCompany();
ProtocolEntity protocol = applicationEntity.getProtocol();
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_GEPAFIN,
call, null);
// Create the map for subject placeholders
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
subjectPlaceholders.put("{{company_name}}", company.getCompanyName());
// Create the map for body placeholders
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{protocol_number}}", protocol.getProtocolNumber().toString());
bodyPlaceholders.put("{{date}}", DateTimeUtil.formatLocalDateTime(protocol.getCreatedDate(), GepafinConstant.DD_MM_YYYY));
bodyPlaceholders.put("{{time}}", DateTimeUtil.parseLocalTimeToString(protocol.getTime(), GepafinConstant.HH_MM_SS));
// Replace placeholders in the subject and body
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
}
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,
MultipartFile file) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
validateFileType(file);
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if (applicationSignedDocument != null) {
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = amazonS3Service.uploadFileOnAmazonS3(signedDocumentS3Folder,
file);
applicationSignedDocument = new ApplicationSignedDocumentEntity();
applicationSignedDocument.setApplication(applicationEntity);
applicationSignedDocument.setFileName(uploadFileOnAmazonS3.getFileName());
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
private ApplicationSignedDocumentResponse convertApplicationSignedDocumentToApplicationSignedDocumentResponse(
ApplicationSignedDocumentEntity applicationSignedDocument) {
ApplicationSignedDocumentResponse applicationSignedDocumentResponse = new ApplicationSignedDocumentResponse();
applicationSignedDocumentResponse.setId(applicationSignedDocument.getId());
applicationSignedDocumentResponse.setApplicationId(applicationSignedDocument.getApplication().getId());
applicationSignedDocumentResponse.setFileName(applicationSignedDocument.getFileName());
applicationSignedDocumentResponse.setFilePath(applicationSignedDocument.getFilePath());
applicationSignedDocumentResponse
.setStatus(ApplicationSignedDocumentStatusEnum.valueOf(applicationSignedDocument.getStatus()));
applicationSignedDocumentResponse.setCreatedDate(applicationSignedDocument.getCreatedDate());
applicationSignedDocumentResponse.setUpdatedDate(applicationSignedDocument.getUpdatedDate());
return applicationSignedDocumentResponse;
}
private void validateFileType(MultipartFile file) {
if (file.isEmpty()) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_EMPTY));
}
String filename = file.getOriginalFilename();
if (filename == null || !filename.endsWith(".p7m")) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_INVALIDTYPE));
}
}
public ApplicationSignedDocumentResponse getSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
public void deleteSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
}

View File

@@ -0,0 +1,131 @@
package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.config.Translator;
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.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 java.util.List;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class BeneficiaryPreferredCallDao {
private final Logger log = LoggerFactory.getLogger(BeneficiaryPreferredCallDao.class);
@Autowired
private BeneficiaryPreferredCallRepository beneficiaryPreferredCallRepository;
@Autowired
private UserService userService;
public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(BeneficiaryPreferredCallReq request,UserEntity user) {
log.info("Creating new beneficiary preferred call with details: {}", request);
BeneficiaryPreferredCallEntity entity = convertRequestToEntity(request,user);
entity = beneficiaryPreferredCallRepository.save(entity);
log.info("Beneficiary preferred call created with ID: {}", entity.getId());
return convertEntityToResponse(entity);
}
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());
}
entity.setStatus(BeneficiaryCallStatus.ENABLED.getValue());
entity.setCallId(request.getCallId());
entity.setUserId(userEntity.getId());
entity.setCompanyId(request.getCompanyId());
return entity;
}
public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(Long id) {
log.info("Fetching beneficiary preferred call with ID: {}", id);
BeneficiaryPreferredCallEntity entity = validateBeneficiaryPreferredCall(id);
log.info("Beneficiary preferred call found: {}", entity);
return convertEntityToResponse(entity);
}
// public BeneficiaryPreferredCallResponseBean updateBeneficiaryPreferredCall(Long id, BeneficiaryPreferredCallReq request,
// UserEntity userEntity) {
// log.info("Updating beneficiary preferred call with ID: {}", id);
// BeneficiaryPreferredCallEntity existingEntity = validateBeneficiaryPreferredCall(id);
// setIfUpdated(existingEntity::getCallId, existingEntity::setCallId, request.getCallId());
// setIfUpdated(existingEntity::getCompanyId, existingEntity::setCompanyId, request.getCompanyId());
//
// existingEntity = beneficiaryPreferredCallRepository.save(existingEntity);
//
// log.info("Beneficiary preferred call updated with ID: {}", existingEntity.getId());
// 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) {
log.info("Deleting beneficiary preferred call with ID: {}", id);
validateBeneficiaryPreferredCall(id);
beneficiaryPreferredCallRepository.deleteById(id);
log.info("Beneficiary preferred call deleted with ID: {}", id);
}
public List<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls() {
log.info("Fetching all beneficiary preferred calls");
List<BeneficiaryPreferredCallResponseBean> calls = beneficiaryPreferredCallRepository.findAll()
.stream()
.map(this::convertEntityToResponse)
.collect(Collectors.toList());
log.info("Total beneficiary preferred calls found: {}", calls.size());
return calls;
}
private BeneficiaryPreferredCallEntity validateBeneficiaryPreferredCall(Long id) {
log.info("Validating beneficiary preferred call with ID: {}", id);
return beneficiaryPreferredCallRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.BENEFICIARY_CALL_NOT_FOUND)));
}
private BeneficiaryPreferredCallResponseBean convertEntityToResponse(BeneficiaryPreferredCallEntity entity) {
BeneficiaryPreferredCallResponseBean response = new BeneficiaryPreferredCallResponseBean();
response.setId(entity.getId());
response.setBeneficiaryId(entity.getBeneficiaryId());
response.setStatus(BeneficiaryCallStatus.valueOf(entity.getStatus()));
response.setCallId(entity.getCallId());
response.setUserId(entity.getUserId());
response.setCompanyId(entity.getCompanyId());
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
return response;
}
public void updateBeneficiaryPreferredCallStatus(Long id, BeneficiaryCallStatus status) {
log.info("Updating status for beneficiary preferred call with ID: {}", id);
BeneficiaryPreferredCallEntity existingEntity = validateBeneficiaryPreferredCall(id);
existingEntity.setStatus(status.getValue());
beneficiaryPreferredCallRepository.save(existingEntity);
log.info("Beneficiary preferred call status updated with ID: {}", existingEntity.getId());
}
public List<BeneficiaryPreferredCallResponseBean> getBeneficiaryPreferredCallByUserId(UserEntity userEntity, Long companyId) {
List<BeneficiaryPreferredCallEntity> calls = beneficiaryPreferredCallRepository.findByUserIdAndCompanyId(userEntity.getId(), companyId);
return calls.stream()
.map(this::convertEntityToResponse)
.collect(Collectors.toList());
}
}

View File

@@ -1,17 +1,27 @@
package net.gepafin.tendermanagement.dao;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.service.*;
import net.gepafin.tendermanagement.util.DateTimeUtil;
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.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -73,20 +83,24 @@ public class CallDao {
@Autowired
private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository;
@Autowired
private UserService userService;
@Autowired
private FaqService faqService;
@Autowired
private FlowDao flowDao;
@Autowired
private FormDao formDao;
@Value("${aws.s3.url.folder}")
private String s3Folder;
@Autowired
private AmazonS3Service amazonS3Service;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) {
UserEntity userEntity = userService.validateUser(userId);
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
CallEntity callEntity = convertToCallEntity(createCallRequest);
CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ);
@@ -98,8 +112,37 @@ public class CallDao {
return createCallResponseBean;
}
public byte[] downloadCallDocumentsAsZip(Long callId) {
List<DocumentEntity> documents = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callId, DocumentSourceTypeEnum.CALL.getValue(),DocumentTypeEnum.DOCUMENT.getValue());
if (documents.isEmpty()) {
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
}
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest) {
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
for (DocumentEntity document : documents) {
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFileName())) {
ZipEntry zipEntry = new ZipEntry(document.getFileName());
zos.putNextEntry(zipEntry);
IOUtils.copy(fileInputStream, zos);
zos.closeEntry();
} catch (IOException e) {
throw new RuntimeException("Error downloading or adding document to ZIP: " + document.getFileName(), e);
}
}
zos.finish();
return zipOutputStream.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Error while creating ZIP file", e);
}
}
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
CallEntity callEntity = new CallEntity();
// validateCallEntity(createCallRequest);
RegionEntity region = regionRepository.findById(createCallRequest.getRegionId())
@@ -124,6 +167,18 @@ public class CallDao {
callEntity.setConfidi(createCallRequest.getConfidi());
}
callEntity.setDocumentationRequested(createCallRequest.getDocumentationRequested());
if (createCallRequest.getAmountMin() != null && createCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) {
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG));
}
callEntity.setAmountMin(createCallRequest.getAmountMin());
if(createCallRequest.getEmail()!=null && Boolean.FALSE.equals(Utils.isValidEmail(createCallRequest.getEmail()))){
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,createCallRequest.getEmail()));
}
callEntity.setEmail(createCallRequest.getEmail());
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;
}
@@ -259,6 +314,11 @@ public class CallDao {
createCallResponseBean.setDocumentationRequested(callEntity.getDocumentationRequested());
createCallResponseBean.setPriorityArea(callEntity.getPriorityArea());
createCallResponseBean.setConfidi(callEntity.getConfidi());
createCallResponseBean.setAmountMin(callEntity.getAmountMin());
createCallResponseBean.setPhoneNumber(callEntity.getPhoneNumber());
createCallResponseBean.setEndTime(callEntity.getEndTime());
createCallResponseBean.setStartTime(callEntity.getStartTime());
createCallResponseBean.setEmail(callEntity.getEmail());
createCallResponseBean.setCreatedDate(callEntity.getCreatedDate());
createCallResponseBean.setUpdatedDate(callEntity.getUpdatedDate());
return createCallResponseBean;
@@ -358,13 +418,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);
@@ -424,8 +482,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"));
@@ -433,7 +490,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,
@@ -456,6 +512,18 @@ public class CallDao {
setIfUpdated(callEntity::getAmountMax, callEntity::setAmountMax, updateCallRequest.getAmountMax());
setIfUpdated(callEntity::getDocumentationRequested, callEntity::setDocumentationRequested,
updateCallRequest.getDocumentationRequested());
if (updateCallRequest.getAmountMin() != null && updateCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) {
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG));
}
if(updateCallRequest.getEmail()!=null && Boolean.FALSE.equals(Utils.isValidEmail(updateCallRequest.getEmail()))){
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,updateCallRequest.getEmail()));
}
setIfUpdated(callEntity::getAmountMin, callEntity::setAmountMin, updateCallRequest.getAmountMin());
setIfUpdated(callEntity::getEmail, callEntity::setEmail, updateCallRequest.getEmail());
setIfUpdated(callEntity::getPhoneNumber, callEntity::setPhoneNumber, updateCallRequest.getPhoneNumber());
setIfUpdated(callEntity::getStartTime, callEntity::setStartTime, DateTimeUtil.parseTime(updateCallRequest.getStartTime()));
setIfUpdated(callEntity::getEndTime, callEntity::setEndTime, DateTimeUtil.parseTime(updateCallRequest.getEndTime()));
setIfUpdated(callEntity::getConfidi, callEntity::setConfidi, updateCallRequest.getConfidi());
updateLookUpData(callEntity, updateCallRequest.getAimedTo(), LookUpDataTypeEnum.AIMED_TO);
updateFaq(updateCallRequest.getFaq(), callEntity, userEntity, LookUpDataTypeEnum.FAQ);
@@ -475,9 +543,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));
@@ -531,6 +599,11 @@ public class CallDao {
callDetailsResponseBean.setThreshold(callEntity.getThreshold());
callDetailsResponseBean.setDocumentationRequested(callEntity.getDocumentationRequested());
callDetailsResponseBean.setPriorityArea(callEntity.getPriorityArea());
callDetailsResponseBean.setAmountMin(callEntity.getAmountMin());
callDetailsResponseBean.setEmail(callEntity.getEmail());
callDetailsResponseBean.setEndTime(callEntity.getEndTime());
callDetailsResponseBean.setStartTime(callEntity.getStartTime());
callDetailsResponseBean.setPhoneNumber(callEntity.getPhoneNumber());
callDetailsResponseBean.setCreatedDate(callEntity.getCreatedDate());
callDetailsResponseBean.setUpdatedDate(callEntity.getUpdatedDate());
return callDetailsResponseBean;
@@ -575,7 +648,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);
@@ -591,8 +664,7 @@ public class CallDao {
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());
@@ -638,6 +710,25 @@ public class CallDao {
Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.CALL_NOT_PUBLISHED));
}
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
if (currentDate.isBefore(callEntity.getStartDate().toLocalDate()) ||
(currentDate.isEqual(callEntity.getStartDate().toLocalDate()) && currentTime.isBefore(callEntity.getStartTime()))) {
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.CALL_NOT_STARTED_YET)
);
}
if (currentDate.isAfter(callEntity.getEndDate().toLocalDate()) ||
(currentDate.isEqual(callEntity.getEndDate().toLocalDate()) && currentTime.isAfter(callEntity.getEndTime()))) {
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.CALL_ALREADY_ENDED)
);
}
return callEntity;
}

View File

@@ -0,0 +1,228 @@
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.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 static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class CompanyDao {
@Autowired
private CompanyRepository companyRepository;
@Autowired
private UserService userService;
@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());
UserWithCompanyEntity userWithCompanyEntity = null;
if (existingCompany != null) {
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), existingCompany.getId())
.orElse(null);
if (existingRelation == null) {
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant());
} else {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY));
}
return convertCompanyEntityToCompanyResponse(existingCompany, userWithCompanyEntity);
} else {
validateCompany(companyRequest);
CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(companyRequest);
companyRepository.save(companyEntity);
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}
}
private void validateCompany(CompanyRequest companyRequest) {
if (Boolean.FALSE.equals(StringUtils.isEmpty(companyRequest.getEmail()))
&& Boolean.FALSE.equals(Utils.isValidEmail(companyRequest.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_EMAIL));
}
if (StringUtils.isEmpty(companyRequest.getVatNumber())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_MANDATORY));
}
if (companyRepository.existsByVatNumber(companyRequest.getVatNumber())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
}
}
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity, Boolean isLegalRepresentant) {
UserWithCompanyEntity userWithCompanyEntity = new UserWithCompanyEntity();
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) {
CompanyEntity entity = new CompanyEntity();
entity.setCompanyName(request.getCompanyName());
entity.setVatNumber(request.getVatNumber());
entity.setCodiceFiscale(request.getCodiceFiscale());
entity.setAddress(request.getAddress());
entity.setPhoneNumber(request.getPhoneNumber());
entity.setCity(request.getCity());
entity.setProvince(request.getProvince());
entity.setCap(request.getCap());
entity.setCountry(request.getCountry());
entity.setPec(request.getPec());
entity.setEmail(request.getEmail());
entity.setNumberOfEmployees(request.getNumberOfEmployees());
entity.setAnnualRevenue(request.getAnnualRevenue());
entity.setContactName(request.getContactName());
entity.setContactEmail(request.getContactEmail());
return entity;
}
private CompanyResponse convertCompanyEntityToCompanyResponse(CompanyEntity entity, UserWithCompanyEntity userWithCompanyEntity) {
CompanyResponse response = new CompanyResponse();
response.setId(entity.getId());
response.setCompanyName(entity.getCompanyName());
response.setVatNumber(entity.getVatNumber());
response.setCodiceFiscale(entity.getCodiceFiscale());
response.setAddress(entity.getAddress());
response.setPhoneNumber(entity.getPhoneNumber());
response.setCity(entity.getCity());
response.setProvince(entity.getProvince());
response.setCap(entity.getCap());
response.setCountry(entity.getCountry());
response.setPec(entity.getPec());
response.setEmail(entity.getEmail());
response.setNumberOfEmployees(entity.getNumberOfEmployees());
response.setAnnualRevenue(entity.getAnnualRevenue());
if(userWithCompanyEntity!=null) {
response.setIsLegalRepresentant(userWithCompanyEntity.getIsLegalRepresentant());
}
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
response.setContactName(entity.getContactName());
response.setContactEmail(entity.getContactEmail());
return response;
}
public CompanyResponse updateCompany(UserEntity userEntity, Long companyId, CompanyRequest companyRequest) {
CompanyEntity companyEntity = validateCompany(companyId);
setIfUpdated(companyEntity::getCompanyName, companyEntity::setCompanyName,
companyRequest.getCompanyName());
setIfUpdated(companyEntity::getVatNumber, companyEntity::setVatNumber, companyRequest.getVatNumber());
setIfUpdated(companyEntity::getCodiceFiscale, companyEntity::setCodiceFiscale,
companyRequest.getCodiceFiscale());
setIfUpdated(companyEntity::getAddress, companyEntity::setAddress, companyRequest.getAddress());
setIfUpdated(companyEntity::getPhoneNumber, companyEntity::setPhoneNumber,
companyRequest.getPhoneNumber());
setIfUpdated(companyEntity::getCity, companyEntity::setCity, companyRequest.getCity());
setIfUpdated(companyEntity::getProvince, companyEntity::setProvince, companyRequest.getProvince());
setIfUpdated(companyEntity::getCap, companyEntity::setCap, companyRequest.getCap());
setIfUpdated(companyEntity::getCountry, companyEntity::setCountry, companyRequest.getCountry());
setIfUpdated(companyEntity::getPec, companyEntity::setPec, companyRequest.getPec());
setIfUpdated(companyEntity::getEmail, companyEntity::setEmail, companyRequest.getEmail());
setIfUpdated(companyEntity::getNumberOfEmployees, companyEntity::setNumberOfEmployees,
companyRequest.getNumberOfEmployees());
setIfUpdated(companyEntity::getAnnualRevenue, companyEntity::setAnnualRevenue,
companyRequest.getAnnualRevenue());
setIfUpdated(companyEntity::getContactName,companyEntity::setContactName,companyRequest.getContactName());
setIfUpdated(companyEntity::getContactEmail,companyEntity::setContactEmail,companyRequest.getContactEmail());
companyRepository.save(companyEntity);
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
Utils.setIfUpdated(userWithCompanyEntity::getIsLegalRepresentant, userWithCompanyEntity::setIsLegalRepresentant,
companyRequest.getIsLegalRepresentant());
userWithCompanyRepository.save(userWithCompanyEntity);
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}
public CompanyEntity validateCompany(Long companyId) {
return companyRepository.findById(companyId).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.COMPANY_NOT_FOUND_MSG)));
}
public CompanyResponse getCompany(UserEntity userEntity, Long companyId) {
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
return convertCompanyEntityToCompanyResponse(validateCompany(companyId), userWithCompanyEntity);
}
public void deleteCompany(UserEntity userEntity, Long companyId) {
CompanyEntity companyEntity = validateCompany(companyId);
companyRepository.delete(companyEntity);
userWithCompanyRepository.deleteByCompanyIdAndIsDeletedFalse(companyId);
}
public List<CompanyResponse> getCompanyByUserId(Long userId) {
UserEntity userEntity = userService.validateUser(userId);
List<Long> activeCompanyIds = userWithCompanyRepository.findActiveCompanyIdsByUserId(userEntity.getId());
List<CompanyEntity> companies = companyRepository.findByIdIn(activeCompanyIds);
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.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
}
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
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

@@ -0,0 +1,118 @@
package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.response.BeneficiaryWidgetResponseBean;
import net.gepafin.tendermanagement.model.response.Widget1;
import net.gepafin.tendermanagement.model.response.SuperAdminWidgetResponseBean;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.repositories.CallRepository;
import net.gepafin.tendermanagement.repositories.CompanyRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class DashboardDao {
@Autowired
private CallRepository callRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private CompanyRepository companyRepository;
public SuperAdminWidgetResponseBean getDashboardWidget() {
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
widgetResponseBean.setWidget1(createWidget1());
// List<Object[]> widgetBars = callRepository.findApplicationsPerCall();
// widgetResponseBean.setWidgetBars(widgetBars);
return widgetResponseBean;
}
private Widget1 createWidget1() {
Widget1 widget1 = initializeWidget1();
setActiveCalls(widget1);
setRegisteredUsers(widget1);
setTotalActiveFinancing(widget1);
setSubmittedApplications(widget1);
setDraftApplications(widget1);
setNumberOfCompanies(widget1);
return widget1;
}
private Widget1 initializeWidget1() {
return Widget1.builder().numberOfActiveCalls(0L).numberOfCompany(0L).numberOfDraftApplications(0L)
.numberOfResgisteredUsers(0L).numberOfSubmittedApplications(0L).totalActiveFinancing(BigDecimal.ZERO)
.build();
}
private void setActiveCalls(Widget1 widget1) {
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
if (activeCalls != null) {
widget1.setNumberOfActiveCalls(activeCalls);
}
}
private void setRegisteredUsers(Widget1 widget1) {
Long activeUsers = userRepository.countByStatusAndRoleEntityRoleType(UserStatusEnum.ACTIVE.getValue(),
RoleStatusEnum.ROLE_BENEFICIARY.getValue());
if (activeUsers != null) {
widget1.setNumberOfResgisteredUsers(activeUsers);
}
}
private void setTotalActiveFinancing(Widget1 widget1) {
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCalls();
widget1.setTotalActiveFinancing(totalActiveFinancing);
}
private void setSubmittedApplications(Widget1 widget1) {
Long submittedApplications = applicationRepository.countSubmittedApplications();
if (submittedApplications != null) {
widget1.setNumberOfSubmittedApplications(submittedApplications);
}
}
private void setDraftApplications(Widget1 widget1) {
Long draftApplications = applicationRepository.countDraftApplications();
if (draftApplications != null) {
widget1.setNumberOfDraftApplications(draftApplications);
}
}
private void setNumberOfCompanies(Widget1 widget1) {
Long numberOfCompanies = companyRepository.countTotalCompanies();
if (numberOfCompanies != null) {
widget1.setNumberOfCompany(numberOfCompanies);
}
}
public BeneficiaryWidgetResponseBean getDashboardWidgetForBeneficiary(UserEntity userEntity,
CompanyEntity company) {
BeneficiaryWidgetResponseBean beneficiaryWidgetResponseBean = BeneficiaryWidgetResponseBean.builder()
.numberOfApplications(0L).numberOfCalls(0L).numberOfIntegratedDocuments(0L).build();
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
if (activeCalls != null) {
beneficiaryWidgetResponseBean.setNumberOfCalls(activeCalls);
}
Long activeApplication = applicationRepository.countSubmittedApplicationsByUserId(userEntity.getId(),
company.getId());
if (activeApplication != null) {
beneficiaryWidgetResponseBean.setNumberOfApplications(activeApplication);
}
return beneficiaryWidgetResponseBean;
}
}

View File

@@ -0,0 +1,256 @@
package net.gepafin.tendermanagement.dao;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity;
import net.gepafin.tendermanagement.entities.UserCompanyDelegationEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
import net.gepafin.tendermanagement.model.request.CompanyDelegationRequest;
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.repositories.DocumentRepository;
import net.gepafin.tendermanagement.repositories.UserCompanyDelegationRepository;
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.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@Component
public class DelegationDao {
private static final String DEFAULT_PLACEHOLDER = "____________________";
@Autowired
private UserService userService;
@Autowired
private CompanyDao companyDao;
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private DocumentRepository documentRepository;
@Value("${aws.s3.url.folder.delegation}")
private String s3Folder;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) {
try {
InputStream templateStream = amazonS3Service.getFile(s3Folder ,templateName);
XWPFDocument doc = loadTemplate(templateStream);
replacePlaceholders(doc, placeholders);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
doc.write(byteArrayOutputStream);
return byteArrayOutputStream;
} catch (Exception e) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.DELEGATION_TEMPLATE_GENERATION_ERROR));
}
}
public void replacePlaceholders(XWPFDocument doc, Map<String, String> placeholders) {
doc.getParagraphs().forEach(paragraph -> {
placeholders.forEach((placeholder, value) -> {
if (paragraph.getText().contains(placeholder)) {
String updatedText = paragraph.getText().replace(placeholder, value);
paragraph.getRuns().forEach(run -> run.setText("", 0)); // Clear the existing text
paragraph.createRun().setText(updatedText); // Insert updated text
}
});
});
}
public XWPFDocument loadTemplate(InputStream templateStream) throws IOException {
return new XWPFDocument(templateStream);
}
public ByteArrayOutputStream downloadCompanyDelegation(UserEntity userEntity, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
Map<String, String> placeholders = getDefaultPlaceholders();
UserResponseBean user = userService.getUserById(userEntity.getId());
CompanyEntity companyEntity = companyDao.validateCompany(companyId);
companyDao.getUserWithCompany(userEntity.getId(), companyId);
updatePlaceholdersForDelegation(user, companyEntity, placeholders, companyDelegationRequest);
DocumentEntity documentEntity = documentRepository.findBySource(GepafinConstant.DELEGATION_TEMPLATE).get(0);
return generateDocument(placeholders, documentEntity.getFileName());
}
private Map<String, String> updatePlaceholdersForDelegation(UserResponseBean user, CompanyEntity companyEntity,
Map<String, String> placeholders, CompanyDelegationRequest companyDelegationRequest) {
validateMandatoryFields(companyDelegationRequest);
addIfNotEmpty(placeholders, "{{company_first_name}}", companyDelegationRequest.getFirstName());
addIfNotEmpty(placeholders, "{{company_last_name}}", companyDelegationRequest.getLastName());
addIfNotEmpty(placeholders, "{{company_codice_fiscale}}", companyDelegationRequest.getCodiceFiscale());
addIfNotEmpty(placeholders, "{{company_name}}", companyEntity.getCompanyName());
addIfNotEmpty(placeholders, "{{company_city}}", companyEntity.getCity());
addIfNotEmpty(placeholders, "{{company_address}}", companyEntity.getAddress());
addIfNotEmpty(placeholders, "{{company_province}}", companyEntity.getProvince());
addIfNotEmpty(placeholders, "{{company_cap}}", companyEntity.getCap());
addIfNotEmpty(placeholders, "{{company_vat_number}}", companyEntity.getVatNumber());
addIfNotEmpty(placeholders, "{{user_first_name}}", user.getFirstName());
addIfNotEmpty(placeholders, "{{user_last_name}}", user.getLastName());
addIfNotNull(placeholders, "{{user_date_of_birth}}", user.getDateOfBirth(),
date -> DateTimeUtil.formatLocalDateTime(date, GepafinConstant.YYYY_MM_DD_SLASH));
addIfNotEmpty(placeholders, "{{user_codice_fiscale}}", user.getCodiceFiscale());
return placeholders;
}
private Map<String, String> getDefaultPlaceholders() {
Map<String, String> placeholders = new HashMap<>();
placeholders.put("{{company_first_name}}", "");
placeholders.put("{{company_last_name}}", "");
placeholders.put("{{company_codice_fiscale}}", "");
placeholders.put("{{company_name}}", "");
placeholders.put("{{company_city}}", "");
placeholders.put("{{company_address}}", "");
placeholders.put("{{company_province}}", "");
placeholders.put("{{company_cap}}", "");
placeholders.put("{{company_vat_number}}", "");
placeholders.put("{{user_first_name}}", "");
placeholders.put("{{user_last_name}}", "");
placeholders.put("{{user_date_of_birth}}", "");
placeholders.put("{{user_codice_fiscale}}", "");
return placeholders;
}
private void validateMandatoryFields(CompanyDelegationRequest companyDelegationRequest) {
if (StringUtils.isAllEmpty(companyDelegationRequest.getFirstName())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_MISSING_FIRSTNAME));
}
if (StringUtils.isAllEmpty(companyDelegationRequest.getLastName())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_MISSING_LASTNAME));
}
if (StringUtils.isAllEmpty(companyDelegationRequest.getCodiceFiscale())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_MISSING_CODICEFISCALE));
}
}
private void addIfNotEmpty(Map<String, String> placeholders, String key, String value) {
if (Boolean.FALSE.equals(StringUtils.isAllEmpty(value))) {
placeholders.put(key, value);
}
}
private <T> void addIfNotNull(Map<String, String> placeholders, String key, T value, Function<T, String> formatter) {
if (value != null) {
placeholders.put(key, formatter.apply(value));
}
}
public CompanyDelegationResponse uploadCompanyDelegation(UserEntity userEntity, Long companyId, MultipartFile file) {
companyDao.validateCompany(companyId);
companyDao.getUserWithCompany(userEntity.getId(), companyId);
validateFileType(file);
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(userEntity.getId(), companyId,
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
if (userCompanyDelegationEntity != null) {
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.INACTIVE.getValue());
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
}
UploadFileOnAmazonS3 uploadFileOnAmazonS3 = uploadFileOnAmazonS3(file);
userCompanyDelegationEntity = new UserCompanyDelegationEntity();
userCompanyDelegationEntity.setCompanyId(companyId);
userCompanyDelegationEntity.setUserId(userEntity.getId());
if (userEntity.getBeneficiary() != null) {
userCompanyDelegationEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.ACTIVE.getValue());
userCompanyDelegationEntity.setFileName(uploadFileOnAmazonS3.fileName());
userCompanyDelegationEntity.setFilePath(uploadFileOnAmazonS3.filepath());
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
return convertUserCompanyDelegationToCompanyDelegationResponse(userCompanyDelegationEntity);
}
private CompanyDelegationResponse convertUserCompanyDelegationToCompanyDelegationResponse(
UserCompanyDelegationEntity userCompanyDelegationEntity) {
return Utils.convertSourceObjectToDestinationObject(userCompanyDelegationEntity, CompanyDelegationResponse.class);
}
private UploadFileOnAmazonS3 uploadFileOnAmazonS3(MultipartFile file){
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String fileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
firstNameContain+=Utils.randomKey(5);
fileName = (firstNameContain + "." + extension);
try {
String filepath = amazonS3Service.upload(fileName, s3Folder, file);
return new UploadFileOnAmazonS3(fileName, filepath);
} catch (Exception e) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
}
private record UploadFileOnAmazonS3(String fileName, String filepath) {
}
private void validateFileType(MultipartFile file) {
if (file.isEmpty()) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_EMPTY));
}
String filename = file.getOriginalFilename();
if (filename == null || !filename.endsWith(".p7m")) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_INVALIDTYPE));
}
}
public CompanyDelegationResponse getCompanyDelegation(UserEntity userEntity, Long companyId) {
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(userEntity.getId(), companyId,
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
companyDao.getUserWithCompany(userEntity.getId(), companyId);
if(userCompanyDelegationEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DELEGATION_NOT_FOUND));
}
return convertUserCompanyDelegationToCompanyDelegationResponse(userCompanyDelegationEntity);
}
public void deleteCompanyDelegation(UserEntity userEntity, Long companyId) {
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(userEntity.getId(), companyId,
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
companyDao.getUserWithCompany(userEntity.getId(), companyId);
if(userCompanyDelegationEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DELEGATION_NOT_FOUND));
}
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.INACTIVE.getValue());
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
}
}

View File

@@ -6,6 +6,7 @@ import java.util.stream.Collectors;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
@@ -40,6 +41,9 @@ public class DocumentDao {
@Autowired
private CallService callService;
@Value("${aws.s3.url.folder}")
private String s3Folder;
public List<DocumentResponseBean> uploadFiles(List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
List<DocumentEntity> documentEntities = new ArrayList<>();
@@ -81,7 +85,7 @@ public class DocumentDao {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
fileName = (firstNameContain + "." + extension);
String filepath = amazonS3Service.upload(fileName, file);
String filepath = amazonS3Service.upload(fileName, s3Folder, file);
uploadFileOnAmazonS3 result = new uploadFileOnAmazonS3(fileName, filepath);
return result;
}
@@ -99,7 +103,7 @@ public class DocumentDao {
private DocumentEntity deleteFileOnAmazonS3(String fileName) {
try {
amazonS3Service.delete(fileName);
amazonS3Service.delete(s3Folder, fileName);
} catch (Exception e) {
}
return null;

View File

@@ -12,8 +12,11 @@ import net.gepafin.tendermanagement.model.request.FaqReq;
import net.gepafin.tendermanagement.model.response.FaqResponseBean;
import net.gepafin.tendermanagement.repositories.FaqRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.LookUpDataService;
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;
@@ -35,12 +38,25 @@ public class FaqDao {
@Autowired
private LookUpDataService lookUpDataService;
@Autowired
private Validator validator;
@Autowired
private CompanyService companyService;
public FaqResponseBean createFaq(FaqReq faqRequest, UserEntity userEntity, Long callId) {
FaqEntity entity = new FaqEntity();
public FaqResponseBean createFaq(FaqReq faqRequest, UserEntity userEntity, Long callId, Long companyId) {
CallEntity callEntity = callService.validateCall(callId);
entity = createOrUpdateFaqEntity(faqRequest, callEntity, userEntity,
FaqEntity entity = createOrUpdateFaqEntity(faqRequest, callEntity, userEntity,
LookUpDataEntity.LookUpDataTypeEnum.FAQ);
if (validator.checkIsBeneficiary() && companyId == null) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.COMPANY_ID_MANDATORY));
}
if(companyId!=null) {
companyService.validateCompany(companyId);
entity.setCompanyId(companyId);
}
faqRepository.save(entity);
return convertToFaqResponseBean(entity);
}

View File

@@ -4,20 +4,16 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.FlowDataEntity;
import net.gepafin.tendermanagement.entities.FlowDataEntity;
import net.gepafin.tendermanagement.entities.FlowEdgesEntity;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import net.gepafin.tendermanagement.model.request.FlowDataRequestBean;
import net.gepafin.tendermanagement.model.request.FlowEdgesRequestBean;
import net.gepafin.tendermanagement.model.request.FlowRequestBean;
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
import net.gepafin.tendermanagement.model.response.FlowDataResponseBean;
import net.gepafin.tendermanagement.model.response.FlowEdgesResponseBean;
import net.gepafin.tendermanagement.model.response.FlowResponseBean;
import net.gepafin.tendermanagement.repositories.CallRepository;
import net.gepafin.tendermanagement.repositories.FlowDataRepository;
import net.gepafin.tendermanagement.repositories.FlowDataRepository;
import net.gepafin.tendermanagement.repositories.FlowEdgesRepository;
import net.gepafin.tendermanagement.repositories.FlowEdgesRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.FormService;
@@ -29,7 +25,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

View File

@@ -1,11 +1,9 @@
package net.gepafin.tendermanagement.dao;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.repositories.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -22,7 +20,6 @@ import net.gepafin.tendermanagement.enums.FormActionEnum;
import net.gepafin.tendermanagement.model.response.NextOrPreviousFormResponse;
import net.gepafin.tendermanagement.service.FormService;
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;
@Component
@@ -46,7 +43,9 @@ public class FlowFormDao {
@Autowired
private FormService formService;
@Autowired
private FormRepository formRepository;
private FormDao formDao;
// Long getNextForm(FormEntity currentFormEntity, ApplicationEntity applicationEntity) {
// // vlaidation if next form findout and cuuent from is not fill the give error
@@ -176,81 +175,83 @@ public class FlowFormDao {
.orElse(null);
}
// public Long getPreviousForm(FormEntity currentFormEntity, ApplicationEntity applicationEntity) {
// // Retrieve the flow edges for the previous forms
// List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByTargetIdAndCallId(
// currentFormEntity.getId(), applicationEntity.getCall().getId());
//
// if (flowEdgesList.isEmpty()) {
// return null;
//// throw new ResourceNotFoundException(Status.NOT_FOUND,
//// Translator.toLocale(GepafinConstant.PREVIOUS_FORM_NOT_FOUND));
// }
//
// // If only one edge exists, return the source form ID
// if (flowEdgesList.size() == 1) {
// return flowEdgesList.get(0).getSourceId();
// }
//
// // For multiple edges, find the previous form based on the chosen value
// List<Long> previousFormIds = flowEdgesList.stream()
// .map(FlowEdgesEntity::getSourceId)
// .toList();
//
// // Fetch the flow data based on previous form IDs
// List<FlowDataEntity> flowDataList = flowDataRepository.findByFormIdInAndCallId(
// previousFormIds, applicationEntity.getCall().getId());
//
// List<String> chosenValues = flowDataList.stream()
// .map(FlowDataEntity::getChoosenValue)
// .toList();
//
// // Fetch the previous forms based on the chosen field values
// Set<FormEntity> formList = applicationFormFieldRepository
// .findByFieldValueInAndApplicationFormApplicationId(chosenValues, applicationEntity.getId()).stream()
// .map(fieldEntity -> fieldEntity.getApplicationForm().getForm())
// .collect(Collectors.toSet());
//
// // Find next form IDs recursively for all forms in the formList
// List<Long> fieldIds = formList.stream()
// .map(formEntity -> getNextForm(formEntity, applicationEntity))
// .toList();
//
// // Return the first matching previous form ID that corresponds to a next form
// return previousFormIds.stream()
// .filter(fieldIds::contains)
// .findFirst().orElse(null);
// }
public Long getPreviousForm(FormEntity currentFormEntity, ApplicationEntity applicationEntity) {
// Retrieve the flow edges for the previous forms
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByTargetIdAndCallId(
currentFormEntity.getId(), applicationEntity.getCall().getId());
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByTargetIdAndCallId(
currentFormEntity.getId(), applicationEntity.getCall().getId());
if (flowEdgesList.isEmpty()) {
return null;
if (flowEdgesList.isEmpty()) {
return null;
// throw new ResourceNotFoundException(Status.NOT_FOUND,
// Translator.toLocale(GepafinConstant.PREVIOUS_FORM_NOT_FOUND));
}
// // If only one edge exists, return the source form ID
// if (flowEdgesList.size() == 1) {
// return flowEdgesList.get(0).getSourceId();
// }
// If only one edge exists, return the source form ID
if (flowEdgesList.size() == 1) {
return flowEdgesList.get(0).getSourceId();
}
// For multiple edges, find the previous form based on the chosen value
List<Long> previousFormIds = flowEdgesList.stream()
.map(FlowEdgesEntity::getSourceId)
.toList();
List<Long> previousFormIds = flowEdgesList.stream()
.map(FlowEdgesEntity::getSourceId)
.toList();
List<ApplicationFormEntity> applicationFormEntities=applicationFormRepository.findByFormIdInAndApplicationId(previousFormIds,applicationEntity.getId());
// Fetch the flow data based on previous form IDs
List<FlowDataEntity> flowDataList = flowDataRepository.findByFormIdInAndCallId(
previousFormIds, applicationEntity.getCall().getId());
applicationFormEntities.sort(Comparator.comparing(ApplicationFormEntity::getCreatedDate).reversed());
List<String> chosenValues = flowDataList.stream()
.map(FlowDataEntity::getChoosenValue)
.toList();
return applicationFormEntities.isEmpty() ? null : applicationFormEntities.get(0).getForm().getId();
// Fetch the previous forms based on the chosen field values
Set<FormEntity> formList = applicationFormFieldRepository
.findByFieldValueInAndApplicationFormApplicationId(chosenValues, applicationEntity.getId()).stream()
.map(fieldEntity -> fieldEntity.getApplicationForm().getForm())
.collect(Collectors.toSet());
// Find next form IDs recursively for all forms in the formList
List<Long> fieldIds = formList.stream()
.map(formEntity -> getNextForm(formEntity, applicationEntity))
.toList();
// Return the first matching previous form ID that corresponds to a next form
return previousFormIds.stream()
.filter(fieldIds::contains)
.findFirst().orElse(null);
}
public NextOrPreviousFormResponse getnextOrPreviousForm(ApplicationEntity applicationEntity, Long formId,
FormActionEnum action) {
// public Long getPreviousForm(FormEntity currentFormEntity, ApplicationEntity applicationEntity) {
//
// List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByTargetIdAndCallId(
// currentFormEntity.getId(), applicationEntity.getCall().getId());
//
// if (flowEdgesList.isEmpty()) {
// return null;
//// throw new ResourceNotFoundException(Status.NOT_FOUND,
//// Translator.toLocale(GepafinConstant.PREVIOUS_FORM_NOT_FOUND));
// }
//
// // // If only one edge exists, return the source form ID
// // if (flowEdgesList.size() == 1) {
// // return flowEdgesList.get(0).getSourceId();
// // }
//
// // For multiple edges, find the previous form based on the chosen value
// List<Long> previousFormIds = flowEdgesList.stream()
// .map(FlowEdgesEntity::getSourceId)
// .toList();
// if (previousFormIds.size() == 1) {
// return previousFormIds.get(0);
// }
//
// List<ApplicationFormEntity> applicationFormEntities=applicationFormRepository.findByFormIdInAndApplicationId(previousFormIds,applicationEntity.getId());
// applicationFormEntities.sort(Comparator.comparing(ApplicationFormEntity::getCreatedDate).reversed());
//
// return applicationFormEntities.isEmpty() ? null : applicationFormEntities.get(0).getForm().getId();
// }
public NextOrPreviousFormResponse getNextOrPreviousForm(ApplicationEntity applicationEntity, Long formId,
FormActionEnum action) {
Long calculatedFormId = null;
FormEntity formEntity = null;
if (formId == null) {
@@ -274,48 +275,93 @@ public class FlowFormDao {
}
}
NextOrPreviousFormResponse nextOrPreviousFormResponse = null;
if (calculatedFormId != null) {
nextOrPreviousFormResponse = setNextOrPreviousResponse(calculatedFormId, applicationEntity);
if (calculatedFormId == null && formId == null) {
FormEntity form=formService.validateForm(applicationEntity.getCall().getInitialForm());
calculatedFormId=form.getId();
}
if (calculatedFormId == null) {
calculatedFormId=formId;
}
nextOrPreviousFormResponse = setNextOrPreviousResponse(calculatedFormId, applicationEntity);
return nextOrPreviousFormResponse;
}
private NextOrPreviousFormResponse setNextOrPreviousResponse(Long calculatedFormId, ApplicationEntity applicationEntity) {
NextOrPreviousFormResponse nextOrPreviousFormResponse = new NextOrPreviousFormResponse();
Integer completedSteps=0;
FormEntity formEntity = formService.validateForm(calculatedFormId);
nextOrPreviousFormResponse.setFormId(calculatedFormId);
nextOrPreviousFormResponse.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(applicationEntity.getStatus()));
nextOrPreviousFormResponse.setApplicationFormResponse(
applicationDao.processForm(formEntity, applicationEntity));
nextOrPreviousFormResponse.setCallId(applicationEntity.getCall().getId());
nextOrPreviousFormResponse.setCallTitle(applicationEntity.getCall().getName());
nextOrPreviousFormResponse.setCompanyId(applicationEntity.getCompany().getId());
nextOrPreviousFormResponse.setCompanyName(applicationEntity.getCompany().getCompanyName());
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalFormSteps = calculateTotalSteps(flowEdgesList);
Long currentStep = calculateCurrentStep(flowEdgesList, formEntity);
nextOrPreviousFormResponse.setTotalFormSteps(totalFormSteps);
completedSteps = getCompletedSteps(applicationEntity);
nextOrPreviousFormResponse.setCompletedSteps(Long.valueOf(completedSteps));
nextOrPreviousFormResponse.setCurrentStep(currentStep);
if(applicationEntity.getProtocol() != null) {
nextOrPreviousFormResponse.setProtocolNumber(applicationEntity.getProtocol().getProtocolNumber());
}
return nextOrPreviousFormResponse;
}
public Integer getCompletedSteps(ApplicationEntity applicationEntity) {
Integer completedSteps=0;
List<ApplicationFormEntity> applicationFormList = applicationFormRepository.findByApplicationId(applicationEntity.getId());
List<ApplicationFormFieldEntity> applicationFormFieldEntities=new ArrayList<>();
for (ApplicationFormEntity applicationFormEntity:applicationFormList){
applicationFormFieldEntities=applicationFormFieldRepository.findByApplicationFormId(applicationFormEntity.getId());
Boolean isCompleted=formDao.validateCompletedSteps(applicationFormFieldEntities, applicationEntity, applicationFormEntity.getForm());
if(Boolean.TRUE.equals(isCompleted)){
completedSteps++;
}
}
return completedSteps;
}
public Long calculateCurrentStep(List<FlowEdgesEntity> flowEdgesList, FormEntity formEntity) {
Long currentStep = 2l;
if (formEntity.getId().equals(formEntity.getCall().getInitialForm())) {
currentStep = 1l;
} else if (flowEdgesList.size()>1 && formEntity.getId().equals(formEntity.getCall().getFinalForm())) {
currentStep = 3l;
}
return currentStep;
}
public Long calculateTotalSteps(List<FlowEdgesEntity> flowEdgesList) {
Long totalFormSteps = 3l;
if (flowEdgesList.size() == 1) {
totalFormSteps = 2l;
}
Long currentStep = 2l;
if (formEntity.getId().equals(formEntity.getCall().getInitialForm())) {
currentStep = 1l;
} else if (formEntity.getId().equals(formEntity.getCall().getFinalForm())) {
currentStep = 3l;
}
List<ApplicationFormEntity> applicationFormList = applicationFormRepository.findByApplicationId(applicationEntity.getId());
nextOrPreviousFormResponse.setTotalFormSteps(totalFormSteps);
nextOrPreviousFormResponse.setCompletedSteps(Long.valueOf(applicationFormList.size()));
nextOrPreviousFormResponse.setCurrentStep(currentStep);
return nextOrPreviousFormResponse;
return totalFormSteps;
}
private Long getDefaultForm(ApplicationEntity applicationEntity) {
List<ApplicationFormEntity> applicationFormList = applicationFormRepository.findByApplicationIdOrderByCreatedDateAsc(applicationEntity.getId());
if(applicationFormList.isEmpty()) {
if (applicationFormList.isEmpty()) {
return applicationEntity.getCall().getInitialForm();
}
if(applicationFormList.get(applicationFormList.size()-1).getForm().getId().equals(applicationEntity.getCall().getFinalForm())) {
return applicationEntity.getCall().getInitialForm();
if (applicationFormList.get(applicationFormList.size() - 1).getForm().getId().equals(applicationEntity.getCall().getFinalForm())) {
return applicationEntity.getCall().getInitialForm();
}
return getNextForm(applicationFormList.get(applicationFormList.size()-1).getForm(), applicationEntity);
FormEntity currentFormEntity = applicationFormList.get(applicationFormList.size() - 1).getForm();
for (ApplicationFormEntity applicationFormEntity : applicationFormList) {
Boolean isCompleted = formDao.validateCompletedSteps(applicationFormFieldRepository.findByApplicationFormId(applicationFormEntity.getId()), applicationEntity, applicationFormEntity.getForm());
if (Boolean.FALSE.equals(isCompleted)) {
return applicationFormEntity.getForm().getId();
}
}
return getNextForm(currentFormEntity, applicationEntity);
}

View File

@@ -6,18 +6,17 @@ 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.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;
@@ -32,9 +31,6 @@ public class FormDao {
@Autowired
private FormRepository formRepository;
@Autowired
private CallService callService;
@Autowired
private ApplicationFormRepository applicationFormRepository;
@@ -52,15 +48,17 @@ public class FormDao {
@Autowired
private CallRepository callRepository;
@Autowired
private Validator validator;
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()));
@@ -73,13 +71,13 @@ public class FormDao {
formResponseBean.setContent(Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class));
formResponseBean.setLabel(formEntity.getLabel());
formResponseBean.setCallId(formEntity.getCall().getId());
formResponseBean.setCallStatus(formEntity.getCall().getStatus());
return formResponseBean;
}
public FormResponseBean createForm(Long callId,FormRequest formRequest){
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);
@@ -87,7 +85,7 @@ public class FormDao {
callEntity.setFinalForm(null);
callRepository.save(callEntity);
}
FormEntity formEntity=convertFormRequestToFormEntity(callId,formRequest);
FormEntity formEntity=convertFormRequestToFormEntity(callEntity, formRequest);
return convertFormEntityToFormResponseBean(formEntity);
}
public void validateForm(FormRequest formRequest){
@@ -95,11 +93,12 @@ public class FormDao {
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.REQUIRED_PARAMETER_NOT_FOUND_FOR_FORM));
}
}
public FormResponseBean updateForm(Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
public FormResponseBean updateForm(UserEntity user, Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
ContentRequestBean contentRequestBean2=null;
String choosenField=null;
FormEntity formEntity = validateForm(formId);
callDao.validateUpdate(formEntity.getCall());
validator.validateUserWithCall(user, formEntity.getCall().getId());
callDao.validateUpdate(formEntity.getCall());
List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(), ContentRequestBean.class);
for (ContentRequestBean contentRequestBean1 : contentRequestBean) {
FlowDataEntity flowDataEntity = flowDataRepository.findByFormIdAndChoosenField(formEntity.getId(), contentRequestBean1.getId());
@@ -140,6 +139,13 @@ public class FormDao {
);
}
}
else {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel, formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
return convertFormEntityToFormResponseBean(formEntity);
}
}
}
}
@@ -162,12 +168,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);
@@ -178,13 +186,12 @@ 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());
@@ -197,29 +204,33 @@ public class FormDao {
public void validateFormField(List<ApplicationFormFieldRequestBean> applicationFormFieldRequestList, ApplicationEntity applicationEntity, FormEntity formEntity) {
Map<String, Object> formFieldMap = new LinkedHashMap<String, Object>();
for(ApplicationFormFieldRequestBean applicationFormFieldRequestBean:applicationFormFieldRequestList) {
formFieldMap.put(applicationFormFieldRequestBean.getFieldId(),applicationFormFieldRequestBean.getFieldValue());
}
if(applicationFormFieldRequestBean.getFieldValue()==null )
continue;
if (applicationFormFieldRequestBean.getFieldValue() != null ) {
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
checkObjectData(applicationFormFieldRequestBean.getFieldId(), fieldValue, formFieldMap);
}}
FormResponseBean formResponseBean = convertFormEntityToFormResponseBean(formEntity);
FormResponseBean formResponseBean = convertFormEntityToFormResponseBean(formEntity);
ApplicationFormEntity applicationFormEntity=applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(),formEntity.getId());
Boolean isApplicationFormExist= getApplicationFormExist(applicationFormEntity);
FieldValidator validator = FieldValidator.create();
formResponseBean.getContent().forEach(contentResponseBean -> {
String fieldId = contentResponseBean.getId();
String value = (String) formFieldMap.get(fieldId);
String fieldLabel=contentResponseBean.getLabel();
if(value == null && isApplicationFormExist) {
return;
}
FieldValidatorBean fieldValidatorBean = Utils.convertSourceObjectToDestinationObject(contentResponseBean.getValidators(), FieldValidatorBean.class);
validator
.isRequired(value,fieldValidatorBean.getIsRequired(),fieldId)
.minLength(value, fieldValidatorBean.getMinLength(), fieldId) // Only applies if minLength is not null
.maxLength(value, fieldValidatorBean.getMaxLength(), fieldId) // Only applies if maxLength is not null
.matchesPattern(value, fieldValidatorBean.getPattern(), fieldId) // Only applies if pattern is present
.validateCustom(value, fieldValidatorBean.getCustom(), fieldId); // Add the custom validation here
.minLength(value, fieldValidatorBean.getMinLength(), fieldLabel) // Only applies if minLength is not null
.maxLength(value, fieldValidatorBean.getMaxLength(), fieldLabel) // Only applies if maxLength is not null
.matchesPattern(value, fieldValidatorBean.getPattern(), fieldLabel) // Only applies if pattern is present
.validateCustom(value, fieldValidatorBean.getCustom(), fieldLabel); // Add the custom validation here
if (fieldValidatorBean.getCustom() != null && fieldValidatorBean.getCustom().equals(GepafinConstant.IS_PIVA)) {
String error = validateVatNumber(value, fieldValidatorBean.getCustom(), fieldId);
String error = validateVatNumber(value, fieldValidatorBean.getCustom(), fieldLabel);
if(error != null) {
validator.addError(error);
}
@@ -228,6 +239,28 @@ public class FormDao {
validator.validate();
}
private void checkObjectData(String fieldId, Object fieldValue, Map<String, Object> formFieldMap) {
if (fieldValue instanceof List<?>) {
List<?> list = (List<?>) fieldValue;
// Only map if the list is not empty and contains Strings
if (!list.isEmpty() && list.get(0) instanceof String) {
for (Object value : list) {
setFormFieldMap(fieldId, formFieldMap, value);
}
}
}
else setFormFieldMap(fieldId, formFieldMap, fieldValue);
}
private void setFormFieldMap(String fieldId, Map<String, Object> formFieldMap, Object value) {
if (value instanceof String) {
if(value !=null && Boolean.FALSE.equals(StringUtils.isEmpty((String)value))) {
formFieldMap.put(fieldId, value);
}
}
}
private Boolean getApplicationFormExist(ApplicationFormEntity applicationFormEntity) {
if(applicationFormEntity !=null) {
return true;
@@ -235,19 +268,43 @@ public class FormDao {
return false;
}
public Boolean validateCompletedSteps(List<ApplicationFormFieldEntity> applicationFormFieldEntityList, ApplicationEntity applicationEntity, FormEntity formEntity) {
Map<String, Object> formFieldMap = new LinkedHashMap<String, Object>();
for(ApplicationFormFieldEntity applicationFormFieldEntity:applicationFormFieldEntityList) {
formFieldMap.put(applicationFormFieldEntity.getFieldId(),applicationFormFieldEntity.getFieldValue());
}
FormResponseBean formResponseBean = convertFormEntityToFormResponseBean(formEntity);
FieldValidator validator = FieldValidator.create();
formResponseBean.getContent().forEach(contentResponseBean -> {
String fieldId = contentResponseBean.getId();
String value = (String) formFieldMap.get(fieldId);
FieldValidatorBean fieldValidatorBean = Utils.convertSourceObjectToDestinationObject(contentResponseBean.getValidators(), FieldValidatorBean.class);
validator
.isRequired(value,fieldValidatorBean.getIsRequired(),fieldId);
});
if (validator.hasErrors()) {
return false; // Validation failed, return false
}
return true;
}
public String validateVatNumber(String value,String customRule,String fieldId){
String error=null;
if (value.matches("^\\d{1,11}$")) {
Map<String, Object> customData=null;
if (value!=null && value.matches("^\\d{1,11}$")) {
// 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));
}
}
return error;
}
}

View File

@@ -0,0 +1,57 @@
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.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(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.findAll(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

@@ -0,0 +1,640 @@
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;
import com.itextpdf.text.Image;
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 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.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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;
@Component
public class PdfDao {
@Autowired
private CallService callService;
@Autowired
private ApplicationDao applicationDao;
@Autowired
private Validator validator;
public byte[] generatePdf(HttpServletRequest request,Long applicationId) {
try {
UserEntity userEntity = validator.validateUser(request);
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
CallEntity call=callService.validateCall(applicationEntity.getCall().getId());
// Create a byte stream to hold the PDF
ByteArrayOutputStream out = new ByteArrayOutputStream();
float leftMargin = 50f; // Adjust this for the left margin
Document document = new Document(PageSize.A4, leftMargin, 36f, 50f, 35);
PdfWriter writer = PdfWriter.getInstance(document, out);
// CustomPageEvent pageEvent = new CustomPageEvent(call.getName(), 0);
// writer.setPageEvent(pageEvent);
document.open();
// pageEvent.setTotalPages(writer.getPageNumber());
addLogo(document, "https://mementoresources.s3.eu-west-1.amazonaws.com/gepafin/logo.jpg"); // Add your image path here
BaseColor customColor = new BaseColor(0, 128, 0); // Adjust RGB values as needed
// Define fonts and styles
BaseColor greenColor = new BaseColor(0, 128, 0); // Adjust RGB values as needed
BaseColor darkGreenColor = new BaseColor(1, 50, 32); // Adjust RGB values as needed
Font titleFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, customColor);
Font sectionFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,darkGreenColor);
Font labelFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,new BaseColor(113,121,126)); // Light grey);
Font smallFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8,new BaseColor(105, 105, 105));
Font valueFont=FontFactory.getFont(FontFactory.HELVETICA_BOLD,10,new BaseColor(178, 190, 181));
Paragraph title = new Paragraph(call.getName(), titleFont);
title.setAlignment(Element.ALIGN_LEFT);
document.add(title);
BaseColor greyColor=new BaseColor(178, 190, 181); // Very light grey color
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);
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());
}
}
addColoredLines(writer,document,greenColor);
document.add(new Paragraph(" ")); // Add line break
}
document.add(new Paragraph("\n")); // Add line break
Font boldSmallFont = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD,new BaseColor(105, 105, 105));
// Adding the "Documenti Allegati" section title
document.add(new Paragraph(" "));
// pageEvent.setTotalPages(writer.getPageNumber());
document.newPage();
// pageEvent.setTotalPages(writer.getPageNumber());
document.add(new Paragraph("Documenti Allegati", sectionFont));
document.add(new Paragraph(" "));
// 1. Autocertificazione possesso Requisiti
Paragraph p1 = new Paragraph();
p1.add(new Chunk("1. ", boldSmallFont));
p1.add(new Chunk("Autocertificazione possesso Requisiti ", boldSmallFont));
p1.add(new Chunk("ai sensi degli artt. 46 e 47 del DPR 445/2000", smallFont));
document.add(p1);
document.add(new Paragraph(" "));
// 2. Informativa Privacy relativa al trattamento dei dati personali
Paragraph p2 = new Paragraph();
p2.add(new Chunk("2. ", boldSmallFont));
p2.add(new Chunk("Informativa Privacy relativa al trattamento dei dati personali", boldSmallFont));
document.add(p2);
document.add(new Paragraph(" "));
// 3. Dati richiesti per la valutazione delladeguatezza dei flussi finanziari
Paragraph p3 = new Paragraph();
p3.add(new Chunk("3. ", boldSmallFont));
p3.add(new Chunk("Dati richiesti per la valutazione delladeguatezza dei flussi finanziari prospettici come da tabella di cui allAppendice 9", boldSmallFont));
document.add(p3);
document.add(new Paragraph(" "));
// 4. Rilevazione Centrale dei Rischi
Paragraph p4 = new Paragraph();
p4.add(new Chunk("4. ", boldSmallFont));
p4.add(new Chunk("Rilevazione Centrale dei Rischi riferita agli ultimi 36 mesi disponibili alla data di presentazione della Domanda", boldSmallFont));
document.add(p4);
document.add(new Paragraph(" "));
// 5. Schema di presentazione dei dati di bilancio
Paragraph p5 = new Paragraph();
p5.add(new Chunk("5. ", boldSmallFont));
p5.add(new Chunk("Schema di presentazione dei dati di bilancio", boldSmallFont));
document.add(p5);
document.add(new Paragraph(" "));
// 6. Dettagli bilanci in forma abbreviata
Paragraph p6 = new Paragraph();
p6.add(new Chunk("6. ", boldSmallFont));
p6.add(new Chunk("Dettagli bilanci in forma abbreviata", boldSmallFont));
document.add(p6);
document.add(new Paragraph(" "));
// 7. Relazione aziendale illustrativa
Paragraph p7 = new Paragraph();
p7.add(new Chunk("7. ", boldSmallFont));
p7.add(new Chunk("Relazione aziendale illustrativa", boldSmallFont));
document.add(p7);
document.add(new Paragraph(" "));
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
byte[] pdfBytes =PdfPageNumberInserter.addPageNumbers(out.toByteArray());
return pdfBytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private Integer addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,String title,Integer totalPages) throws DocumentException {
// Add label
Paragraph labelParagraph = new Paragraph(label, labelFont);
document.add(labelParagraph);
float leftMargin = 20f;
PdfContentByte canvas = writer.getDirectContent();
// Setting the color and width of the line
float lineWidth = 1.0f; // Thickness of the line
canvas.setLineWidth(lineWidth);
// Get the current vertical position in the document
float yPos = writer.getVerticalPosition(true) - 10f; // Adjust this to move line slightly below current content
// Define start and end points for the line (relative to the page size and margins)
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
// Create value cell with rounded corners
PdfPTable valueTable = new PdfPTable(1);
valueTable.setWidthPercentage(100);
if (value instanceof List<?>) {
// Further check if the list contains Strings
List<?> list = (List<?>) value;
if (!list.isEmpty() && list.get(0) instanceof String) {
// Cast to List<String>
List<String> values = (List<String>) value;
// Loop through the list of strings and create a cell for each string
for (String item : values) {
PdfPCell valueCell = new PdfPCell(new Phrase(item, valueFont));
valueCell.setPadding(5f); // Increase padding for better spacing
valueCell.setPaddingLeft(leftMargin); // Increase left margin for value
valueCell.setBorder(Rectangle.NO_BORDER); // Remove border for value cell
valueCell.setMinimumHeight(30f);
valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
valueCell.setCellEvent(new RoundedCorners()); // Apply rounded corners
// Add the cell to the table
valueTable.addCell(valueCell);
}
// 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
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);
}
}
else {
PdfPCell valueCell = new PdfPCell(new Phrase(String.valueOf(value), valueFont));
valueCell.setPadding(5f); // Increase padding for better spacing
valueCell.setPaddingLeft(leftMargin); // Increase left margin for value
valueCell.setBorder(Rectangle.NO_BORDER); // Remove border for value cell
valueCell.setMinimumHeight(30f);
valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
valueCell.setCellEvent(new RoundedCorners()); // Apply rounded corners
valueTable.addCell(valueCell);
document.add(valueTable);
}
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
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 maxTableHeight = 700f; // Maximum height of the table before a page break
float[] columnWidths = {0.7f, 0.3f};
table.setWidths(columnWidths);
// 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
// Check if the current entry is for the combined section
if ("combined".equals(key)) {
// Ensure the combined header is added only once
if (!combinedHeaderAdded) {
// Create a new table for combined entries
table = new PdfPTable(3); // 3 columns for combined entries
PdfPCell headerCell1 = new PdfPCell(new Phrase("Number"));
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell1);
PdfPCell headerCell2 = new PdfPCell(new Phrase("Details"));
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell2);
PdfPCell headerCell3 = new PdfPCell(new Phrase("Amount"));
headerCell3.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell3.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell3);
combinedHeaderAdded = true; // Mark header as added
}
// Split the value for "combined" into separate parts
String[] combinedValues = value.split("; ");
// Check if we have 3 parts (number, description, amount)
String number = combinedValues[0]; // 1st part (number)
String description = combinedValues[1]; // 2nd part (description)
String amount = "";
if (combinedValues.length == 3) {
amount = combinedValues[2]; // 3rd part (amount)
}
// Create PDF cells using the split values
PdfPCell cellNumber = new PdfPCell(new Phrase(number, textFont)); // Cell for number
PdfPCell cellDescription = new PdfPCell(new Phrase(description, textFont)); // Cell for description
PdfPCell cellAmount = new PdfPCell(new Phrase(amount, textFont)); // Cell for amount
// Set row background color for combined values
cellNumber.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for combined rows
cellDescription.setBackgroundColor(new BaseColor(239, 243, 248));
cellAmount.setBackgroundColor(new BaseColor(239, 243, 248));
// Set cell height and add rounded borders
// cellNumber.setFixedHeight(rowHeight);
// cellDescription.setFixedHeight(rowHeight);
// cellAmount.setFixedHeight(rowHeight);
cellNumber.setMinimumHeight(20f); // Set minimum height for better appearance
cellDescription.setMinimumHeight(20f); // Set minimum height for better appearance
cellAmount.setMinimumHeight(20f); // Set minimum height for better appearance
cellNumber.setPadding(7f);
cellDescription.setPadding(7f);
cellAmount.setPadding(7f);
// Add the cells to the table only once
table.addCell(cellNumber);
table.addCell(cellDescription);
table.addCell(cellAmount);
} else {
if (!combinedHeaderAdded) {
// Create a new table for combined entries
table= new PdfPTable(2); // 3 columns for combined entries
table.setWidthPercentage(100);
PdfPCell headerCell1 = new PdfPCell(new Phrase("Details"));
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell1);
PdfPCell headerCell2 = new PdfPCell(new Phrase("Amount"));
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell2);
combinedHeaderAdded=true;
}
// Add cells for regular key-value pairs without headers
PdfPCell cellKey = new PdfPCell(new Phrase(key, textFont));
PdfPCell cellValue = new PdfPCell(new Phrase(value, textFont));
// Set background color for both cells
cellKey.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for other rows
cellValue.setBackgroundColor(new BaseColor(239, 243, 248));
cellKey.setPadding(7f);
cellValue.setPadding(7f);
// Set cell height and add rounded borders
cellKey.setFixedHeight(rowHeight);
cellValue.setFixedHeight(rowHeight);
// Add the cells to the table
table.addCell(cellKey);
table.addCell(cellValue);
}
if (table.getTotalHeight() + rowHeight > maxTableHeight) {
// Start a new page if needed
document.add(table);
table = new PdfPTable(2); // Reset table for new page
table.setWidthPercentage(100); // Reset width percentage
combinedHeaderAdded = false; // Reset header flag
}
}
}
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,
int headerRows, int rowStart, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.BASECANVAS];
// Get the table boundaries
float left = widths[0][0];
float right = widths[0][widths[0].length - 1];
float top = heights[0];
float bottom = heights[heights.length - 1];
// Define the corner radius
float radius = 20f;
// Draw a rounded rectangle around the table
canvas.roundRectangle(left, bottom, right - left, top - bottom, radius);
canvas.stroke();
}
}
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean) {
List<FieldLabelValuePairRequest> labelValuePairs = new ArrayList<>();
// Iterate through each form in the application response
List<ApplicationFormFieldResponseBean> formFields = responseBean.getFormFields();
List<ContentResponseBean> contents = responseBean.getContent();
// Iterate through each formField in the current form
for (ApplicationFormFieldResponseBean formField : formFields) {
String fieldId = formField.getFieldId();
Object fieldValue = formField.getFieldValue();
// Find the content in the form that matches the fieldId
Optional<ContentResponseBean> matchingContent = contents.stream()
.filter(content -> content.getId().equals(fieldId))
.findFirst();
// If the content with the matching fieldId is found, create a label-value pair
if (matchingContent.isPresent()) {
String name = matchingContent.get().getName();
if (name.equals("fileupload")) {
// 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
.collect(Collectors.toList());
fieldValue=names;
}
}
if(name.equals("checkboxes")) {
List<String> check = (List<String>) fieldValue;
List<SettingResponseBean> settingResponseBeans = matchingContent.get().getSettings();
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
// Initialize a list to hold matched labels for each SettingResponseBean
List<String> matchedLabels = new ArrayList<>();
if (settingResponseBean.getValue() instanceof List<?>) {
List<?> valueList = (List<?>) settingResponseBean.getValue();
if (!valueList.isEmpty() && valueList.get(0) instanceof Map<?, ?>) {
// Cast to List<Map<String, String>>
List<Map<String, String>> options = (List<Map<String, String>>) valueList;
for (Map<String, String> field : options) {
for (String val : check) {
String name1=field.get("name");
if (val.equals(name1)) { // Check if the key exists in the current field map
String label = field.get("label"); // Extract the label
if (field != null) { // Check if the value is not null
matchedLabels.add(label); // Add the value to the matchedValues list
}
}
}
}
fieldValue = matchedLabels;
}
}
}
}
String label = matchingContent.get().getLabel();
// Add the label-value pair to the list
if (fieldValue != null && !fieldValue.toString().trim().isEmpty()) {
fieldValue = findLabelInOptions(matchingContent.get().getSettings(), fieldValue);
labelValuePairs.add(new FieldLabelValuePairRequest(label, fieldValue));
}
}
}
return labelValuePairs;
}
public static Object findLabelInOptions(List<SettingResponseBean> settings, Object valueToFind) {
ObjectMapper objectMapper = new ObjectMapper();
try {
if (valueToFind instanceof String) {
String searchValue = (String) valueToFind;
for (SettingResponseBean setting : settings) {
Object value = setting.getValue();
if (value instanceof List) {
List<?> options = (List<?>) value;
for (Object option : options) {
JsonNode optionNode = objectMapper.convertValue(option, JsonNode.class);
if (optionNode.get("name").asText().equals(searchValue)) {
return optionNode.get("label").asText();
}
}
}
}
}
} catch (Exception e) {
}
return valueToFind;
}
public void addLogo(Document document, String logoPath) throws Exception {
Image logo = Image.getInstance(logoPath);
logo.scaleToFit(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(), // Fit to document width
document.getPageSize().getHeight() / 4); // Adjust the height as needed (1/4th of the page height)
logo.setAlignment(Image.ALIGN_CENTER); // Align logo to center
document.add(logo);
// Add some space after logo
document.add(new Paragraph("\n")); // Adding space after the logo
}
public void addColoredLines(PdfWriter writer, Document document, BaseColor color){
PdfContentByte canvas = writer.getDirectContent();
// Setting the color and width of the line
canvas.setColorStroke(color);
float lineWidth = 1.0f; // Thickness of the line
canvas.setLineWidth(lineWidth);
// Get the current vertical position in the document
float yPos = writer.getVerticalPosition(true) - 10f; // Adjust this to move line slightly below current content
// Define start and end points for the line (relative to the page size and margins)
float xStart = document.leftMargin(); // Start from the left margin
float xEnd = document.getPageSize().getWidth() - document.rightMargin(); // End at the right margin
// Draw the line at the current Y position
canvas.moveTo(xStart, yPos); // Move to the starting point
canvas.lineTo(xEnd, yPos); // Draw the line to the end point
canvas.stroke(); // Apply the stroke (line)
}
}

View File

@@ -0,0 +1,45 @@
package net.gepafin.tendermanagement.dao;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfContentByte;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class PdfPageNumberInserter {
public static byte[] addPageNumbers(byte[] pdfData) throws IOException, DocumentException {
PdfReader reader = new PdfReader(pdfData); // Read the generated PDF
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BaseColor darkGreenColor = new BaseColor(1, 50, 32); // Adjust RGB values as needed
Font baseFont = FontFactory.getFont(FontFactory.HELVETICA, 4,darkGreenColor);
BaseFont font = baseFont.getBaseFont();
// PdfStamper allows us to modify the existing PDF
PdfStamper stamper = new PdfStamper(reader, outputStream);
int totalPages = reader.getNumberOfPages();
// Set the font for page numbers
for (int i = 1; i <= totalPages; i++) {
// Get the content of the current page
PdfContentByte over = stamper.getOverContent(i);
over.beginText();
over.setFontAndSize(font, 12);
// Add the page number at the bottom center of the page
over.showTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + i + " of " + totalPages, 300, 30, 0);
over.endText();
}
stamper.close();
reader.close();
return outputStream.toByteArray(); // Return the modified PDF with page numbers
}
}

View File

@@ -4,6 +4,7 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.RegionEntity;
import net.gepafin.tendermanagement.entities.RoleEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.model.request.RoleReq;
import net.gepafin.tendermanagement.model.response.RegionResponseBean;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
@@ -119,4 +120,8 @@ public class RoleDao {
log.info("Total roles found: {}", roles.size());
return roles;
}
public RoleEntity getRoleByType(RoleStatusEnum roleStatus) {
return roleRepository.findByRoleType(roleStatus.getValue());
}
}

View File

@@ -0,0 +1,45 @@
package net.gepafin.tendermanagement.dao;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPCellEvent;
import com.itextpdf.text.pdf.PdfPTable;
public class RoundedCorners implements PdfPCellEvent {
@Override
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvas) {
// Retrieve the canvas for drawing the background and border
PdfContentByte cbBackground = canvas[PdfPTable.BACKGROUNDCANVAS];
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cbBackground.saveState();
cb.saveState();
// Define the rounded rectangle radius and padding
float radius = 10f;
float padding = 2f; // Small padding to avoid overlap
// Get position values with adjusted height and width
float x = position.getLeft() + padding;
float y = position.getBottom() + padding;
float width = position.getWidth() - 2 * padding;
float height = position.getHeight() - 2 * padding;
// Fill the rounded rectangle with lighter grey
cbBackground.setColorFill(new BaseColor(239, 243, 248)); // Very light grey color
cbBackground.roundRectangle(x, y, width, height, radius);
cbBackground.fill(); // Fill the background
// Set the border stroke to thin and draw the rounded rectangle with dark grey color
cb.setLineWidth(0.5f); // Thin border width
cb.setColorStroke(new BaseColor(105, 105, 105)); // Dark grey border
cb.roundRectangle(x, y, width, height, radius);
cb.stroke(); // Draw the border
// Restore the canvas states
cbBackground.restoreState();
cb.restoreState();
}
}

View File

@@ -0,0 +1,116 @@
package net.gepafin.tendermanagement.dao;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum;
import net.gepafin.tendermanagement.model.response.SystemEmailTemplateResponse;
import net.gepafin.tendermanagement.repositories.SystemEmailTemplatesRespository;
import net.gepafin.tendermanagement.util.Utils;
@Component
public class SystemEmailTemplatesDao {
@Autowired
private SystemEmailTemplatesRespository systemEmailTemplatesRespository;
@Value("${fe.base.url}")
private String feBaseUrl;
public SystemEmailTemplateResponse retrieveTemplate(SystemEmailTemplatesEntityTypeEnum type, CallEntity call, Locale language) {
SystemEmailTemplatesEntity dbSystemEmailTemplatesEntity = null;
if(call != null){
// dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
// .findByTypeAndCallId(type.getValue(), call.getId());
}
if(dbSystemEmailTemplatesEntity == null){
dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
.findByType(type.getValue());
}
SystemEmailTemplateResponse systemEmailTemplateResponse = replaceHtmlContant(dbSystemEmailTemplatesEntity, call, language, Boolean.TRUE);
return systemEmailTemplateResponse;
}
private SystemEmailTemplateResponse replaceHtmlContant(SystemEmailTemplatesEntity dbSystemEmailTemplatesEntity,
CallEntity call, Locale language1, Boolean isDefaultReplace) {
String language = null;
String htmlContent = dbSystemEmailTemplatesEntity.getHtmlContent();
String subject = dbSystemEmailTemplatesEntity.getSubject();
if (language1 == null) {
// language = getLanguage(LocaleContextHolder.getLocale());
language="italian";
}else{
language="italian";
}
Map<String, String> languageMap = new HashMap<>();
String jsonContent = dbSystemEmailTemplatesEntity.getJson();
if (Boolean.FALSE.equals(StringUtils.isEmpty(jsonContent))) {
Map<String, Map<String, String>> jsonMap = Utils.parseJsonContent(jsonContent);
if (jsonMap != null && jsonMap.containsKey(language)) {
languageMap = jsonMap.get(language);
htmlContent = replacePlaceholders(htmlContent, languageMap);
subject = replaceSubjectPlaceholders(subject, languageMap);
}
}
if(Boolean.TRUE.equals(StringUtils.isEmpty(subject))){
subject = "";
}
htmlContent = replacePlatformLinkPlaceholder(call, htmlContent, languageMap);
SystemEmailTemplateResponse systemEmailTemplateResponse = new SystemEmailTemplateResponse();
systemEmailTemplateResponse.setHtmlContent(htmlContent);
systemEmailTemplateResponse.setSubject(subject);
systemEmailTemplateResponse.setJsonMap(languageMap);
return systemEmailTemplateResponse;
}
// private String getLanguage(Locale locale) {
// return switch (locale.getLanguage()) {
// case "en" -> "english";
// case "it" -> "italian";
// default -> "italian";
// };
// }
private String replacePlaceholders(String htmlContent, Map<String, String> languageMap) {
for (Map.Entry<String, String> entry : languageMap.entrySet()) {
htmlContent = htmlContent.replace("{{" + entry.getKey() + "}}", entry.getValue());
}
return htmlContent;
}
private String replaceSubjectPlaceholders(String subject, Map<String, String> languageMap) {
if(languageMap.containsKey("subject") && subject != null){
String value = languageMap.get("subject");
subject = subject.replace("{{subject}}", value);
return subject;
}
return "";
}
private String replacePlatformLinkPlaceholder(CallEntity call, String htmlContent,
Map<String, String> languageMap) {
String platformLink = feBaseUrl;
// if(hubEntity != null && Boolean.FALSE.equals(isEmpty(hubEntity.getDomainName()))){
// platformLink = hubEntity.getDomainName();
// }
htmlContent = htmlContent.replace("{{platform_link}}", platformLink);
return htmlContent;
}
}

View File

@@ -4,68 +4,158 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
import net.gepafin.tendermanagement.entities.RoleEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.entities.UserHubEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.UserHubRepository;
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.RoleService;
import net.gepafin.tendermanagement.service.impl.AuthenticationService;
import net.gepafin.tendermanagement.util.Utils;
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.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.Repository;
import java.security.SecureRandom;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Repository
@Component
public class UserDao {
private final Logger log = LoggerFactory.getLogger(UserDao.class);
@Autowired
private UserRepository userRepository;
@Autowired
private CompanyDao companyDao;
@Autowired
private AuthenticationService authService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserHubRepository userHubRepository;
@Autowired
private RoleDao roleDao;
@Autowired
private BeneficiaryRepository beneficiaryRepository;
@Autowired
private RoleService roleService;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
public UserResponseBean createUser(UserReq userReq) {
log.info("Creating user with email: {}", userReq.getEmail());
if (userRepository.existsByEmailIgnoreCase(userReq.getEmail())) {
log.error("User creation failed: Email {} already exists", userReq.getEmail());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
if(StringUtils.isEmpty(userReq.getHubUuid())) {
userReq.setHubUuid(defaultHubUuid);
}
validateUserRequest(tempToken, userReq);
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
RoleEntity roleEntity = getRoleEntity(userReq.getRoleId());
BeneficiaryEntity beneficiary = createBeneficiary(roleEntity, userReq);
UserEntity userEntity = convertUserRequestToUserEntity(beneficiary, roleEntity, userReq);
log.info("User created with ID: {}", userEntity.getId());
return authService.getJWTTokenBean(userEntity, Boolean.TRUE);
}
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq) {
BeneficiaryEntity beneficiaryEntity = null;
if (RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType())) {
beneficiaryEntity = new BeneficiaryEntity();
beneficiaryEntity.setAddress(userReq.getAddress());
beneficiaryEntity.setCity(userReq.getCity());
beneficiaryEntity.setCodiceFiscale(userReq.getCodiceFiscale());
beneficiaryEntity.setCountry(userReq.getCountry());
beneficiaryEntity.setDateOfBirth(userReq.getDateOfBirth());
beneficiaryEntity.setEmail(userReq.getEmail());
beneficiaryEntity.setFirstName(userReq.getFirstName());
beneficiaryEntity.setLastName(userReq.getLastName());
beneficiaryEntity.setOrganization(userReq.getOrganization());
beneficiaryEntity.setPhoneNumber(userReq.getPhoneNumber());
beneficiaryEntity.setPrivacy(userReq.getPrivacy());
beneficiaryEntity.setTerms(userReq.getTerms());
beneficiaryEntity.setOffers(userReq.getOffers());
beneficiaryEntity.setMarketing(userReq.getMarketing());
beneficiaryEntity.setThirdParty(userReq.getThirdParty());
beneficiaryEntity.setEmailPec(userReq.getEmailPec());
beneficiaryEntity =beneficiaryRepository.save(beneficiaryEntity);
}
return beneficiaryEntity;
}
private void validateUserRequest(String tempToken, UserReq userReq) {
RoleEntity role = roleService.validateRole(userReq.getRoleId());
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.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())) {
log.error("User creation failed: CodiceFiscale {} already exists", userReq.getCodiceFiscale());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CODICE_FISCALE_EXISTS));
}
if (tempToken == null && userReq.getRoleId() == null) {
throw new ResourceNotFoundException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.ROLE_ID_MANDATORY));
}
if (tempToken != null) {
userReq.setRoleId(null);
}
if(tempToken == null && Boolean.TRUE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(role.getRoleType()))){
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CANNOT_CREATE_BENEFICIARY_USER));
}
if (!userReq.getPassword().equals(userReq.getConfPassword())) {
log.error("User creation failed: Passwords do not match for email {}", userReq.getEmail());
}
private void validatePassword(String password, String confirmPassword, String tempToken) {
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPassword)) {
if(tempToken == null) {
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.VALIDATE_PASSWORD));
}else if(Boolean.FALSE.equals(StringUtils.isEmpty(password) && StringUtils.isEmpty(confirmPassword))){
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.VALIDATE_PASSWORD));
}
}
if (password != null && !password.equals(confirmPassword)) {
log.error("User creation failed: Passwords do not match");
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
}
if (userReq.getPassword().length() < 8) {
log.error("User creation failed: Password length is less than 8 characters for email {}", userReq.getEmail());
if (password != null && password.length() < 8) {
log.error("User creation failed: Password length is less than 8 characters");
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_MIN_LEN));
}
UserEntity userEntity = convertUserRequestToUserEntity(userReq);
userEntity = userRepository.save(userEntity);
log.info("User created with ID: {}", userEntity.getId());
return convertUserEntityToUserResponse(userEntity);
}
public UserResponseBean updateUser(Long userId, UpdateUserReq userReq) {
@@ -82,59 +172,101 @@ public class UserDao {
setIfUpdated(userEntity::getOrganization, userEntity::setOrganization, userReq.getOrganization());
setIfUpdated(userEntity::getAddress, userEntity::setAddress, userReq.getAddress());
setIfUpdated(userEntity::getPhoneNumber, userEntity::setPhoneNumber, userReq.getPhoneNumber());
setIfUpdated(userEntity::getDateOfBirth, userEntity::setDateOfBirth, userReq.getDateOfBirth());
setIfUpdated(userEntity.getBeneficiary()::getCodiceFiscale, userEntity.getBeneficiary()::setCodiceFiscale, userReq.getCodiceFiscale());
setIfUpdated(userEntity.getBeneficiary()::getMarketing, userEntity.getBeneficiary()::setMarketing, userReq.getMarketing());
setIfUpdated(userEntity.getBeneficiary()::getOffers, userEntity.getBeneficiary()::setOffers, userReq.getOffers());
setIfUpdated(userEntity.getBeneficiary()::getThirdParty, userEntity.getBeneficiary()::setThirdParty, userReq.getThirdParty());
if (userReq.getRoleId() != null) {
RoleEntity roleEntity = roleDao.validateRole(userReq.getRoleId());
setIfUpdated(userEntity::getRoleEntity, userEntity::setRoleEntity, roleEntity);
}
setIfUpdated(userEntity.getBeneficiary()::getEmailPec, userEntity.getBeneficiary()::setEmailPec, userReq.getEmailPec());
userEntity = userRepository.save(userEntity);
log.info("User updated with ID: {}", userEntity.getId());
return convertUserEntityToUserResponse(userEntity);
}
private UserEntity convertUserRequestToUserEntity(UserReq userReq) {
private UserEntity convertUserRequestToUserEntity(BeneficiaryEntity beneficiary, RoleEntity roleEntity, UserReq userReq) {
UserEntity userEntity = new UserEntity();
userEntity.setPassword(passwordEncoder.encode(userReq.getPassword()));
if(Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getPassword()))) {
userEntity.setPassword(passwordEncoder.encode(userReq.getPassword()));
}
userEntity.setRoleEntity(roleEntity);
userEntity.setEmail(userReq.getEmail());
userEntity.setFirstName(userReq.getFirstName());
userEntity.setStatus(UserStatusEnum.PENDING_VERIFICATION.getValue());
userEntity.setLastName(userReq.getLastName());
userEntity.setOrganization(userReq.getOrganization());
userEntity.setAddress(userReq.getAddress());
userEntity.setPhoneNumber(userReq.getPhoneNumber());
userEntity.setRoleEntity(roleDao.validateRole(userReq.getRoleId()));
return userEntity;
userEntity.setStatus(UserStatusEnum.ACTIVE.getValue());
userEntity.setBeneficiary(beneficiary);
if (Boolean.FALSE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType()))) {
userEntity.setFirstName(userReq.getFirstName());
userEntity.setLastName(userReq.getLastName());
userEntity.setOrganization(userReq.getOrganization());
userEntity.setAddress(userReq.getAddress());
userEntity.setPhoneNumber(userReq.getPhoneNumber());
userEntity.setDateOfBirth(userReq.getDateOfBirth());
}
return userRepository.save(userEntity);
}
private UserResponseBean convertUserEntityToUserResponse(UserEntity userEntity) {
UserResponseBean userResponseBean = new UserResponseBean();
userResponseBean.setId(userEntity.getId());
userResponseBean.setCreatedDate(userEntity.getCreatedDate());
userResponseBean.setUpdatedDate(userEntity.getUpdatedDate());
userResponseBean.setEmail(userEntity.getEmail());
userResponseBean.setFirstName(userEntity.getFirstName());
userResponseBean.setLastName(userEntity.getLastName());
userResponseBean.setPhoneNumber(userEntity.getPhoneNumber());
userResponseBean.setOrganization(userEntity.getOrganization());
userResponseBean.setAddress(userEntity.getAddress());
userResponseBean.setCity(userEntity.getCity());
userResponseBean.setCountry(userEntity.getCountry());
userResponseBean.setStatus(UserStatusEnum.valueOf(userEntity.getStatus()));
RoleResponseBean roleResponseBean = roleDao.convertRoleEntityToRoleResponse(userEntity.getRoleEntity());
userResponseBean.setRole(roleResponseBean);
userResponseBean.setLastLogin(userEntity.getLastLogin());
return userResponseBean;
}
private RoleEntity getRoleEntity(Long roleId) {
if(roleId != null) {
return roleDao.validateRole(roleId);
} else {
return roleDao.getRoleByType(RoleStatusEnum.ROLE_BENEFICIARY);
}
}
public UserResponseBean getUserById(Long id) {
log.info("Fetching user with ID: {}", id);
UserEntity userEntity=validateUser(id);
private UserResponseBean convertUserEntityToUserResponse(UserEntity userEntity) {
UserResponseBean userResponseBean = new UserResponseBean();
userResponseBean.setId(userEntity.getId());
userResponseBean.setCreatedDate(userEntity.getCreatedDate());
userResponseBean.setUpdatedDate(userEntity.getUpdatedDate());
userResponseBean.setEmail(userEntity.getEmail());
userResponseBean.setStatus(UserStatusEnum.valueOf(userEntity.getStatus()));
RoleResponseBean roleResponseBean = roleDao.convertRoleEntityToRoleResponse(userEntity.getRoleEntity());
userResponseBean.setRole(roleResponseBean);
userResponseBean.setLastLogin(userEntity.getLastLogin());
List<CompanyResponse> companyResponseBeans = companyDao.getCompanyByUserId(userEntity.getId());
userResponseBean.setCompanies(companyResponseBeans);
if (userEntity.getBeneficiary() == null) {
userResponseBean.setFirstName(userEntity.getFirstName());
userResponseBean.setLastName(userEntity.getLastName());
userResponseBean.setPhoneNumber(userEntity.getPhoneNumber());
userResponseBean.setOrganization(userEntity.getOrganization());
userResponseBean.setAddress(userEntity.getAddress());
userResponseBean.setCity(userEntity.getCity());
userResponseBean.setCountry(userEntity.getCountry());
userResponseBean.setDateOfBirth(userEntity.getDateOfBirth());
} else {
userResponseBean.setFirstName(userEntity.getBeneficiary().getFirstName());
userResponseBean.setLastName(userEntity.getBeneficiary().getLastName());
userResponseBean.setPhoneNumber(userEntity.getBeneficiary().getPhoneNumber());
userResponseBean.setOrganization(userEntity.getBeneficiary().getOrganization());
userResponseBean.setAddress(userEntity.getBeneficiary().getAddress());
userResponseBean.setCity(userEntity.getBeneficiary().getCity());
userResponseBean.setCountry(userEntity.getBeneficiary().getCountry());
userResponseBean.setCodiceFiscale(userEntity.getBeneficiary().getCodiceFiscale());
userResponseBean.setDateOfBirth(userEntity.getBeneficiary().getDateOfBirth());
userResponseBean.setPrivacy(userEntity.getBeneficiary().getPrivacy());
userResponseBean.setTerms(userEntity.getBeneficiary().getTerms());
userResponseBean.setOffers(userEntity.getBeneficiary().getOffers());
userResponseBean.setMarketing(userEntity.getBeneficiary().getMarketing());
userResponseBean.setThirdParty(userEntity.getBeneficiary().getThirdParty());
userResponseBean.setEmailPec(userEntity.getBeneficiary().getEmailPec());
}
return userResponseBean;
}
public UserResponseBean getUserById(Long id) {
log.info("Fetching user with ID: {}", id);
UserEntity userEntity = validateUser(id);
// if (!UserStatusEnum.ACTIVE.getValue().equals(userEntity.getStatus())) {
// log.info("User with ID: {} is not active", id);
// throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
// }
log.info("User found: {}", userEntity);
return convertUserEntityToUserResponse(userEntity);
}
log.info("User found: {}", userEntity);
return convertUserEntityToUserResponse(userEntity);
}
public void deleteUser(Long id) {
log.info("Deleting user with ID: {}", id);
@@ -143,9 +275,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;
}
@@ -155,22 +290,22 @@ public class UserDao {
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
}
public String generateSecureToken() {
SecureRandom secureRandom = new SecureRandom();
byte[] tokenBytes = new byte[24];
secureRandom.nextBytes(tokenBytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
log.debug("Generated secure token: {}", token);
return token;
public UserEntity getUserByBeneficiaryId(Long beneficiaryId) {
UserEntity user = userRepository.findByBeneficiaryId(beneficiaryId);
if (user == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_WITH_BENEFICIARYID_MSG));
}
return user;
}
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));
}
String token = generateSecureToken();
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);
log.info("Password reset token generated for user: {}", resetReq.getEmail());
@@ -178,11 +313,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));
@@ -201,12 +336,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));
}
@@ -232,24 +367,41 @@ public class UserDao {
return convertUserEntityToUserResponse(userEntity);
}
public List<UserResponseBean> getUserByHubId(String hubId) {
log.info("Fetching users for hub ID: {}", hubId);
List<UserHubEntity> userHubMappings = userHubRepository.findByHubId(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));
}
// for (UserHubEntity mapping : userHubMappings) {
// UserEntity userEntity = validateUser(mapping.getUserId());
// userResponseBeans.add(convertUserEntityToUserResponse(userEntity));
// }
return userResponseBeans;
}
public UserResponseBean createUserByHubId(String hubId, UserReq userReq) {
log.info("Creating user for hub ID: {}", hubId);
UserResponseBean createdUser = createUser(userReq);
UserHubEntity mapping = new UserHubEntity();
mapping.setHubId(hubId);
mapping.setUserId(createdUser.getId());
userHubRepository.save(mapping);
log.info("User created and mapped to hub ID: {} with User ID: {}", hubId, createdUser.getId());
return createdUser;
public JWTToken validateExistingUserToken(String token) {
return authService.validateExistingUserToken(token);
}
public UserSamlResponse validateNewUserToken(String token) {
return authService.validateNewUserToken(token);
}
public List<UserResponseBean> getAllUsers(Long roleId) {
List<UserEntity> users;
if (roleId != null) {
log.info("Fetching users by role ID: {}", roleId);
RoleEntity roleEntity=roleService.validateRole(roleId);
users = userRepository.findByRoleEntityId(roleEntity.getId());
} else {
log.info("Fetching all users");
users = userRepository.findAll();
}
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

@@ -1,8 +1,13 @@
package net.gepafin.tendermanagement.dao;
import feign.FeignException;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.service.feignClient.VatCheckService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -67,8 +72,17 @@ public class VatCheckDao {
}
} catch (FeignException ex) {
log.error("Exception occurred while checking vat number: {0}", ex);
throw ex;
Utils.callException(ex.status(), ex);
}
return responseBody;
}
public Map<String, Object> checkVatNumber(String vatNumber) {
try {
return checkVatNumberApi(vatNumber);
} catch (Exception e) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
}
}
}