Files
bflows-bandi-be/src/main/java/net/gepafin/tendermanagement/dao/ApplicationEvaluationDao.java
2025-02-27 19:11:27 +05:30

2424 lines
141 KiB
Java

package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.enums.*;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.*;
import net.gepafin.tendermanagement.util.*;
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.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.gepafin.tendermanagement.util.Utils.log;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class ApplicationEvaluationDao {
@Autowired
private ApplicationEvaluationRepository applicationEvaluationRepository;
@Autowired
private ApplicationService applicationService;
@Autowired
private CallRepository callRepository;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private UserService userService;
// @Autowired
// private CallService callService;
@Autowired
private EvaluationCriteriaRepository evaluationCriteriaRepository;
@Autowired
private FormRepository formRepository;
@Autowired
private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository;
@Autowired
private DocumentRepository documentRepository;
@Autowired
private ApplicationFormRepository applicationFormRepository;
@Autowired
private ApplicationFormFieldRepository applicationFormFieldRepository;
@Autowired
private AssignedApplicationsRepository assignedApplicationsRepository;
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
@Autowired
private EmailNotificationDao emailNotificationDao;
@Autowired
ApplicationAmendmentRequestRepository applicationAmendmentRequestRepository;
@Autowired
private FormDao formDao;
@Autowired
private AssignedApplicationsService assignedApplicationsService;
@Autowired
private LoggingUtil loggingUtil;
@Autowired
private HttpServletRequest request;
@Autowired
private CompanyService companyService;
@Autowired
private NotificationDao notificationDao;
@Autowired
private UserRepository userRepository;
@Autowired
private Validator validator;
@Autowired
private DocumentService documentService;
@Autowired
private ApplicationAmendmentRequestDao applicationAmendmentRequestDao;
@Autowired
private HubService hubService;
@Autowired
private EvaluationFormService evaluationFormService;
@Autowired
private EvaluationFormDao evaluationFormDao;
@Autowired
private ApplicationEvaluationFormRepository applicationEvaluationFormRepository;
@Autowired
private ApplicationEvaluationFormFieldRepository applicationEvaluationFormFieldRepository;
@Autowired
private ApplicationDao applicationDao;
@Autowired
private ApplicationEvaluationService applicationEvaluationService;
@Autowired
private CallDao callDao;
@Autowired
private EvaluationFormRepository evaluationFormRepository;
@Autowired
private ObjectMapper objectMapper;
private ApplicationEvaluationEntity convertToEntity(UserEntity user, ApplicationEvaluationRequest req, Long assignedApplciationId) {
ApplicationEvaluationEntity entity = new ApplicationEvaluationEntity();
AssignedApplicationsEntity assignedApplications = assignedApplicationsService.validateAssignedApplication(assignedApplciationId);
ApplicationEntity application = applicationService.validateApplication(assignedApplications.getApplication().getId());
Long hubId = application.getHubId();
HubEntity hub = hubService.valdateHub(hubId);
Long initialDays = (hub != null) ? hub.getEvaluationExpirationDays() : 30L;
entity.setApplicationId(application.getId());
entity.setAssignedApplicationsEntity(assignedApplications);
entity.setUserId(user.getId());
entity.setCriteria(Utils.convertObjectToJson(req.getCriteria()));
entity.setChecklist(Utils.convertObjectToJson(req.getChecklist()));
entity.setFile(Utils.convertObjectToJson(req.getFiles()));
entity.setNote(req.getNote());
entity.setMotivation(req.getMotivation());
entity.setIsDeleted(false);
entity.setInitialDays(initialDays);
entity.setRemainingDays(initialDays);
entity.setSuspendedDays(0L);
entity.setStartDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
entity.setEndDate(DateTimeUtil.DateServerToUTC(application.getSubmissionDate().plusDays(initialDays)));
entity.setEvaluationVersion(application.getEvaluationVersion());
entity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
return entity;
}
private ApplicationEvaluationResponse convertToResponse(ApplicationEvaluationEntity entity) {
ApplicationEvaluationResponse response = new ApplicationEvaluationResponse();
populateBasicDetails(entity, response);
CallEntity call = callRepository.findCallEntityByApplicationId(entity.getApplicationId());
List<EvaluationCriteriaEntity> evaluationCriterias = evaluationCriteriaRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue());
List<CallTargetAudienceChecklistEntity> checklistEntities = callTargetAudienceChecklistRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue());
List<ApplicationFormEntity> applicationFormEntities = applicationFormRepository.findByApplicationId(entity.getApplicationId());
setAmendmentDetails(entity,response);
setCriteriaResponses(entity, response, evaluationCriterias);
setChecklistResponses(entity, response, checklistEntities);
setFieldResponses(entity, response, applicationFormEntities);
List<EvaluationDocumentRequest> allDocs = prepareEvaluationDocumentBeanList(entity);
setEvaluationDocResponse(response, allDocs);
setApplicationDetails(response, entity);
return response;
}
private void setAmendmentDetails(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response) {
List<ApplicationAmendmentRequestEntity> amendmentRequests=applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(entity.getId());
List<AmendmentDocumentResponseBean> amendmentDocumentResponseBeans=new ArrayList<>();
for(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity:amendmentRequests){
AmendmentDocumentResponseBean amendmentDocumentResponseBean=new AmendmentDocumentResponseBean();
amendmentDocumentResponseBean.setAmendmentId(applicationAmendmentRequestEntity.getId());
String amendmentDocument=applicationAmendmentRequestEntity.getAmendmentDocument();
String formField=applicationAmendmentRequestEntity.getFormFields();
AmendmentDetailsResponseBean amendmentDetails = Utils.convertStringToObject(amendmentDocument, AmendmentDetailsResponseBean.class);
if (amendmentDetails != null) {
if (amendmentDetails.getAmendmentDocuments() != null) {
List<DocumentResponseBean> documentResponseBeans = Arrays.stream(amendmentDetails.getAmendmentDocuments().split(","))
.map(String::trim)
.filter(id -> !id.isEmpty())
.map(documentId -> applicationAmendmentRequestDao.createDocumentResponseBean(documentId))
.filter(Objects::nonNull)
.collect(Collectors.toList());
amendmentDocumentResponseBean.setFileDetail(documentResponseBeans);
}
amendmentDocumentResponseBean.setFieldId("amend_" + applicationAmendmentRequestEntity.getId());
amendmentDocumentResponseBean.setLabel(amendmentDetails.getAmendmentNotes());
amendmentDocumentResponseBean.setValid(amendmentDetails.getValid());
amendmentDocumentResponseBeans.add(amendmentDocumentResponseBean);
}
List<AmendmentFormField> amendmentFormFields = Utils.convertJsonStringToList(formField, AmendmentFormField.class);
if (amendmentFormFields != null) {
for (AmendmentFormField amendmentFormField : amendmentFormFields) {
// Skip fields with null or empty fieldValue
if (StringUtils.isEmpty(amendmentFormField.getFieldValue())) {
continue;
}
AmendmentDocumentResponseBean formFieldResponseBean = new AmendmentDocumentResponseBean();
formFieldResponseBean.setAmendmentId(applicationAmendmentRequestEntity.getId());
formFieldResponseBean.setFieldId(amendmentFormField.getFieldId());
formFieldResponseBean.setLabel(amendmentFormField.getLabel());
formFieldResponseBean.setValid(amendmentFormField.getValid());
List<Long> fileIds = applicationAmendmentRequestDao.extractIds(amendmentFormField.getFieldValue());
List<DocumentResponseBean> documentResponseBeans = fileIds.stream()
.map(fileId -> createDocumentResponseBean(documentService.validateDocument(fileId)))
.collect(Collectors.toList());
formFieldResponseBean.setFileDetail(documentResponseBeans);
amendmentDocumentResponseBeans.add(formFieldResponseBean);
}
}
}
response.setAmendmentDetails(amendmentDocumentResponseBeans);
}
private void setEvaluationDocResponse(ApplicationEvaluationResponse response, List<EvaluationDocumentRequest> docRequest) {
List<EvaluationDocumentResponse> evaluationDocResponses = new ArrayList<>();
for (EvaluationDocumentRequest doc : docRequest) {
EvaluationDocumentResponse evaluationDocResponse = new EvaluationDocumentResponse();
if (doc.getFileValue() != null) {
Long fileId = Long.valueOf(doc.getFileValue().toString());
documentRepository.findByIdAndNotDeleted(fileId).ifPresent(documentEntity -> {
DocumentResponseBean documentResponseBean = new DocumentResponseBean();
documentResponseBean.setId(documentEntity.getId());
documentResponseBean.setName(documentEntity.getFileName());
documentResponseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
documentResponseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
documentResponseBean.setSourceId(documentEntity.getSourceId());
documentResponseBean.setFilePath(documentEntity.getFilePath());
documentResponseBean.setCreatedDate(documentEntity.getCreatedDate());
documentResponseBean.setUpdatedDate(documentEntity.getUpdatedDate());
documentResponseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
evaluationDocResponse.setFileValue(List.of(documentResponseBean));
evaluationDocResponse.setNameValue(doc.getNameValue());
evaluationDocResponse.setValid(doc.getValid());
evaluationDocResponse.setFieldId(doc.getFieldId());
});
}
if (evaluationDocResponse.getFileValue() == null) {
continue;
}
evaluationDocResponses.add(evaluationDocResponse);
}
response.setEvaluationDocument(evaluationDocResponses);
}
private void populateBasicDetails(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response) {
response.setId(entity.getId());
response.setApplicationId(entity.getApplicationId());
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByIdAndIsDeletedFalse(entity.getAssignedApplicationsEntity().getId()).orElse(null);
response.setAssignedApplicationId(assignedApplications.getId());
response.setNote(entity.getNote());
response.setMotivation(entity.getMotivation());
response.setStatus(ApplicationEvaluationStatusTypeEnum.valueOf(entity.getStatus()));
response.setEvaluationVersion(EvaluationVersionEnum.valueOf(entity.getEvaluationVersion()));
response.setEvaluationEndDate(entity.getEndDate());
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
response.setNumberOfCheck(entity.getAssignedApplicationsEntity().getApplication().getCall().getNumberOfCheck());
response.setAppointmentTemplateId(entity.getAssignedApplicationsEntity().getApplication().getCall().getAppointmentTemplateId());
}
private void setCriteriaResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List<EvaluationCriteriaEntity> evaluationCriterias) {
List<CriteriaResponse> criteriaResponsesFromEntity = entity.getCriteria() != null ?
Utils.convertJsonToList(entity.getCriteria(), new TypeReference<List<CriteriaResponse>>() {}) :
new ArrayList<>();
List<CriteriaResponse> criteriaResponsesFromDB = getCriteriaResponse(entity.getApplicationId());
addMissingCriteriaResponses(criteriaResponsesFromEntity, criteriaResponsesFromDB, entity.getApplicationId());
criteriaResponsesFromEntity = criteriaResponsesFromEntity.stream()
.filter(criteriaResponse -> {
EvaluationCriteriaEntity matchingEvaluationCriteria = evaluationCriterias.stream()
.filter(evaluationCriteria -> evaluationCriteria.getId().equals(criteriaResponse.getId())) // Find matching criteria by ID
.findFirst()
.orElse(null);
if (matchingEvaluationCriteria != null) {
criteriaResponse.setLabel(matchingEvaluationCriteria.getLookupData().getValue());
criteriaResponse.setMaxScore(matchingEvaluationCriteria.getScore());
List<CriteriaMappedField> mappedFields = getMappedFieldsForCriteria(matchingEvaluationCriteria.getId(), entity.getApplicationId());
criteriaResponse.setCriteriaMappedFields(mappedFields);
return true;
}
return false;
})
.collect(Collectors.toList());
response.setCriteria(criteriaResponsesFromEntity);
}
private void addMissingCriteriaResponses(List<CriteriaResponse> criteriaResponsesFromEntity, List<CriteriaResponse> criteriaResponsesFromDB, Long applicationId) {
Set<Long> existingCriteriaIds = criteriaResponsesFromEntity.stream().map(CriteriaResponse::getId).collect(Collectors.toSet());
for (CriteriaResponse dbResponse : criteriaResponsesFromDB) {
if (!existingCriteriaIds.contains(dbResponse.getId())) {
List<CriteriaMappedField> mappedFields = getMappedFieldsForCriteria(dbResponse.getId(), applicationId);
dbResponse.setCriteriaMappedFields(mappedFields);
criteriaResponsesFromEntity.add(dbResponse);
}
}
}
private List<CriteriaMappedField> getMappedFieldsForCriteria(Long evaluationCriteriaId, Long applicationId) {
List<CriteriaFormFieldEntity> criteriaFormFields = criteriaFormFieldRepository.findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaId);
List<CriteriaMappedField> mappedFields = new ArrayList<>();
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationId);
for (ApplicationFormEntity applicationForm : applicationForms) {
Set<String> uniqueFieldIds = new HashSet<>();
for (CriteriaFormFieldEntity formField : criteriaFormFields) {
String formFieldId = formField.getFormFieldId();
FormEntity formEntity = applicationForm.getForm();
if (formEntity == null || !formEntity.getId().equals(formField.getFormId())) {
continue;
}
if (!uniqueFieldIds.contains(formFieldId)) {
CriteriaMappedField mappedField = new CriteriaMappedField();
mappedField.setId(formFieldId);
List<ContentResponseBean> contentBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class);
contentBeans.stream()
.filter(contentBean -> contentBean.getId().equals(formFieldId))
.findFirst()
.ifPresent(contentBean -> {
mappedField.setFieldLabel(getLabelForField(contentBean));
mappedField.setFieldName(contentBean.getName());
switch (contentBean.getName()) {
case "fileupload":
mapFileFieldDetails(mappedField, formFieldId, applicationForm.getId(), applicationId);
break;
case "checkboxes":
populateOptionFieldsAsFieldValue(mappedField, formFieldId, applicationForm, applicationId, contentBean);
break;
case "paragraph":
handleParagraphField(applicationId, formField, contentBean, mappedField);
break;
case "table":
handleTableField(applicationId, formField, contentBean, mappedField);
break;
default:
populateOptionFieldsAsFieldValue(mappedField, formFieldId, applicationForm, applicationId, contentBean);
}
});
mappedFields.add(mappedField);
uniqueFieldIds.add(formFieldId);
}
}
}
return mappedFields;
}
private FormEntity getFormEntity(Long formId) {
return formRepository.findById(formId).orElse(null);
}
private String getLabelForField(ContentResponseBean contentBean) {
String label = contentBean.getLabel();
if (contentBean.getSettings() != null) {
for (SettingResponseBean setting : contentBean.getSettings()) {
if ("label".equals(setting.getName())) {
label = setting.getValue() != null ? setting.getValue().toString() : label;
break;
}
}
}
return label;
}
private void mapFileFieldDetails(CriteriaMappedField mappedField, String formFieldId, Long applicationFormId, Long applicationId) {
Optional<ApplicationFormFieldEntity> formFieldEntityOptional = applicationFormFieldRepository
.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(formFieldId, applicationFormId, applicationId);
if (formFieldEntityOptional.isPresent() && formFieldEntityOptional.get().getFieldValue()!=null && Boolean.FALSE.equals(formFieldEntityOptional.get()
.getFieldValue().isEmpty())) {
String[] documentIds = formFieldEntityOptional.get().getFieldValue().split(",");
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
for (String docId : documentIds) {
if (Boolean.FALSE.equals(docId.isEmpty())){
Long documentId = Long.valueOf(docId.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
DocumentResponseBean responseBean = new DocumentResponseBean();
responseBean.setId(documentEntity.getId());
responseBean.setName(documentEntity.getFileName());
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
responseBean.setSourceId(documentEntity.getSourceId());
responseBean.setFilePath(documentEntity.getFilePath());
responseBean.setCreatedDate(documentEntity.getCreatedDate());
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
documentResponseBeans.add(responseBean);
});
}
}
mappedField.setFieldValue(documentResponseBeans);
}
}
private void mapNonFileFieldDetails(CriteriaMappedField mappedField, String formFieldId, Long applicationFormId, Long applicationId) {
applicationFormFieldRepository
.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(formFieldId, applicationFormId, applicationId)
.ifPresent(field -> mappedField.setFieldValue(field.getFieldValue()));
}
private void setChecklistResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List<CallTargetAudienceChecklistEntity> checklistEntities) {
List<ChecklistResponse> checklistResponsesFromEntity = entity.getChecklist() != null ?
Utils.convertJsonToList(entity.getChecklist(), new TypeReference<List<ChecklistResponse>>() {}) :
new ArrayList<>();
List<ChecklistResponse> checklistResponsesFromDB = getChecklistResponse(entity.getApplicationId());
addMissingChecklistResponses(checklistResponsesFromEntity, checklistResponsesFromDB);
checklistResponsesFromEntity = checklistResponsesFromEntity.stream()
.filter(checklistResponse -> {
CallTargetAudienceChecklistEntity matchingChecklist = checklistEntities.stream()
.filter(checklistEntity -> checklistEntity.getId().equals(checklistResponse.getId())) // Find matching checklist by ID
.findFirst()
.orElse(null);
if (matchingChecklist != null) {
checklistResponse.setLabel(matchingChecklist.getLookupData().getValue());
return true;
}
return false;
})
.collect(Collectors.toList());
response.setChecklist(checklistResponsesFromEntity);
}
private void addMissingChecklistResponses(List<ChecklistResponse> checklistResponsesFromEntity, List<ChecklistResponse> checklistResponsesFromDB) {
Set<Long> existingChecklistIds = checklistResponsesFromEntity.stream().map(ChecklistResponse::getId).collect(Collectors.toSet());
for (ChecklistResponse dbResponse : checklistResponsesFromDB) {
if (!existingChecklistIds.contains(dbResponse.getId())) {
checklistResponsesFromEntity.add(dbResponse);
}
}
}
private void setFieldResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List<ApplicationFormEntity> applicationFormEntities) {
List<FieldResponse> fieldResponsesFromEntity = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference<List<FieldResponse>>() {}) : new ArrayList<>();
List<FieldResponse> fieldResponsesFromDB = getFieldResponses(entity.getApplicationId());
addMissingFieldResponses(fieldResponsesFromEntity, fieldResponsesFromDB);
Set<String> processedFieldIds = new HashSet<>();
List<FieldResponse> validFieldResponses = new ArrayList<>();
fieldResponsesFromEntity.forEach(fieldResponse -> {
if (processedFieldIds.contains(fieldResponse.getId())) {
return;
}
final Boolean[] allDocumentsDeleted = {true};
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
applicationFormEntities.forEach(applicationForm -> {
FormEntity formEntity = applicationForm.getForm();
if (formEntity != null) {
// Convert the form to a list of content response beans
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
contentResponseBeans.forEach(contentResponseBean -> {
// Check if this is a file upload field that matches the current field response
if ("fileupload".equals(contentResponseBean.getName()) && contentResponseBean.getId().equals(fieldResponse.getId())) {
String label = null;
// Set the label if available
if (contentResponseBean.getSettings() != null) {
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
if ("label".equals(setting.getName())) {
label = setting.getValue() != null ? setting.getValue().toString() : label;
break;
}
}
}
fieldResponse.setLabel(label);
Optional<ApplicationFormFieldEntity> optionalFormField =
applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
fieldResponse.getId(), applicationForm.getId(), entity.getApplicationId());
if (optionalFormField.isPresent()) {
ApplicationFormFieldEntity formField = optionalFormField.get();
if (formField.getFieldValue() != null) {
String[] documentIds = formField.getFieldValue().split(",");
for (String docId : documentIds) {
if (!docId.trim().isEmpty()) {
Long documentId = Long.valueOf(docId.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
if (documentEntity != null && !documentEntity.getIsDeleted()) {
DocumentResponseBean responseBean = new DocumentResponseBean();
responseBean.setId(documentEntity.getId());
responseBean.setName(documentEntity.getFileName());
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
responseBean.setSourceId(documentEntity.getSourceId());
responseBean.setFilePath(documentEntity.getFilePath());
responseBean.setCreatedDate(documentEntity.getCreatedDate());
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
documentResponseBeans.add(responseBean);
allDocumentsDeleted[0] = false;
}
});
}
}
}
}
}
});
}
});
if (Boolean.FALSE.equals(allDocumentsDeleted[0]) && Boolean.FALSE.equals(documentResponseBeans.isEmpty())) {
fieldResponse.setFileDetail(documentResponseBeans);
validFieldResponses.add(fieldResponse);
}
processedFieldIds.add(fieldResponse.getId());
});
response.setFiles(validFieldResponses);
}
private void addMissingFieldResponses(List<FieldResponse> fieldResponsesFromEntity, List<FieldResponse> fieldResponsesFromDB) {
Set<String> existingFieldIds = fieldResponsesFromEntity.stream().map(FieldResponse::getId).collect(Collectors.toSet());
for (FieldResponse dbResponse : fieldResponsesFromDB) {
if (!existingFieldIds.contains(dbResponse.getId())) {
fieldResponsesFromEntity.add(dbResponse);
}
}
}
private void setApplicationDetails(ApplicationEvaluationResponse response, ApplicationEvaluationEntity entity) {
ApplicationEntity application = applicationService.validateApplication(entity.getApplicationId() != null ? entity.getApplicationId() : null);
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository
.findByApplicationIdAndIsDeletedFalse(entity.getApplicationId()).orElse(null);
UserEntity user = userService.validateUser(application.getUserId());
CallEntity call = callRepository.findCallEntityByApplicationId(entity.getApplicationId());
String firstName = user.getBeneficiary().getFirstName() != null ? user.getBeneficiary().getFirstName() : "";
String lastName = user.getBeneficiary().getLastName() != null ? user.getBeneficiary().getLastName() : "";
String beneficiary = String.join(" ", firstName, lastName).trim();
response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(application.getStatus()));
response.setBeneficiary(beneficiary);
response.setNdg(application.getNdg() != null ? application.getNdg() : null);
response.setAppointmentId(application.getAppointmentId() != null ? application.getAppointmentId() : null);
response.setSubmissionDate(application.getSubmissionDate());
response.setMinScore(call.getThreshold() != null ? call.getThreshold() : null);
response.setCallName(application.getCall().getName() != null ? application.getCall().getName() : null);
response.setProtocolNumber((application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null) ? application.getProtocol().getProtocolNumber() : null);
if (assignedApplications != null) {
response.setAssignedAt(assignedApplications.getAssignedAt());
}
response.setEvaluationEndDate(entity.getEndDate());
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(application.getId());
if(assignedApplicationsOptional.isPresent()){
response.setAssignedUserId(assignedApplicationsOptional.get().getUserId());
UserEntity assignedUser = userService.validateUser(assignedApplicationsOptional.get().getUserId());
String assignedUserFirstName = assignedUser.getFirstName() != null ? assignedUser.getFirstName() : "";
String assignedUserLastName = assignedUser.getLastName() != null ? assignedUser.getLastName() : "";
String userName = String.join(" ", assignedUserFirstName, assignedUserLastName).trim();
response.setAssignedUserName(userName);
}
LocalDateTime callEndDate = application.getCall().getEndDate();
response.setCallEndDate(callEndDate);
if (application.getCompanyId() != null) {
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
response.setCompanyName(company.getCompanyName());
}
response.setAmountAccepted(application.getAmountAccepted());
response.setAmountRequested(application.getAmountRequested());
response.setDateAccepted(application.getDateAccepted());
response.setDateRejected(application.getDateRejected());
}
public ApplicationEvaluationResponse createOrUpdateApplicationEvaluation(
UserEntity user,
ApplicationEvaluationRequest req,
Long assignedApplicationId) {
Optional<ApplicationEvaluationEntity> existingEntityOptional =
applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId);
ApplicationEvaluationEntity entity = null;
Optional<AssignedApplicationsEntity> assignedApplications =
assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId);
ApplicationEvaluationEntity oldApplicationEvaluation = null;
ApplicationEntity application = applicationService.validateApplication(assignedApplications.get().getApplication().getId());
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
validateApplicationEvaluationRequest(req, application);
if (existingEntityOptional.isPresent()) {
entity = existingEntityOptional.get();
oldApplicationEvaluation = Utils.getClonedEntityForData(entity);
if(req.getCriteria()!=null) {
entity.setCriteria(Utils.convertObjectToJson(processCriteria(entity, req)));
}
if(req.getChecklist()!=null) {
entity.setChecklist(Utils.convertObjectToJson(processChecklist(entity, req)));
}
if(req.getFiles()!=null) {
entity.setFile(Utils.convertObjectToJson(processField(entity, req)));
}
entity.setIsDeleted(false);
setIfUpdated(entity::getNote, entity::setNote, req.getNote());
setIfUpdated(entity::getMotivation, entity::setMotivation, req.getMotivation());
if(req.getApplicationStatus()!=null && (Boolean.TRUE.equals(req.getApplicationStatus().equals(ApplicationStatusForEvaluation.APPROVED)) && (req.getAmountAccepted()==null || req.getAmountAccepted().compareTo(BigDecimal.ZERO) < 0))){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.AMOUNT_ACCEPTED_REQUIRED_WHILE_APPROVING_APPLICATION));
}
if (req.getAmountAccepted() != null && req.getAmountAccepted().compareTo(BigDecimal.ZERO) > 0) {
application.setAmountAccepted(req.getAmountAccepted());
}
actionType = VersionActionTypeEnum.UPDATE;
entity = applicationEvaluationRepository.save(entity);
} else {
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsService.validateAssignedApplication(assignedApplicationId);
entity = convertToEntity(user, req, assignedApplicationId);
actionType = VersionActionTypeEnum.INSERT;
entity = applicationEvaluationRepository.save(entity);
ApplicationEntity oldApplication = Utils.getClonedEntityForData(application);
application.setApplicationEvaluationId(entity.getId());
/** This code is responsible for adding a version history log for the "Update Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplication).newData(application).build());
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_CREATION);
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_CREATION);
notificationDao.sendNotificationToInstructor(placeHolders,entity,NotificationTypeEnum.EVALUATION_CREATION);
}
/** This code is responsible for adding a version history log for the "Update Application Evaluation" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplicationEvaluation).newData(entity).build());
ApplicationStatusForEvaluation status = req.getApplicationStatus();
// Fetch all amendment request entities associated with the evaluation ID
List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities =
applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(entity.getId());
if(req.getEvaluationDocument()!=null) {
updateApplicationEvaluation(assignedApplicationId, req.getEvaluationDocument());
}
// Fetch amendment details from the request
if(req.getAmendmentDetails()!=null) {
List<AmendmentDetailsRequest> amendmentDetailsRequests = req.getAmendmentDetails();
updateAmendmentDocumentsAndFormFields(applicationAmendmentRequestEntities, amendmentDetailsRequests);
}
if (status != null) {
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplications.get();
return updateApplicationEvaluationStatus(application, assignedApplicationsEntity, status);
} else {
return convertToResponse(entity);
}
}
private void validateApplicationEvaluationRequest(ApplicationEvaluationRequest req, ApplicationEntity application) {
if(EvaluationVersionEnum.V2.getValue().equals(application.getEvaluationVersion())) {
req.setChecklist(null);
req.setCriteria(null);
}
}
private void updateAmendmentDocumentsAndFormFields(List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities, List<AmendmentDetailsRequest> amendmentFormFields) {
// Iterate through amendment request entities
//
Map<Long,List<AmendmentDetailsRequest>> amendmentFormFieldsMap = amendmentFormFields.stream().collect(Collectors.groupingBy(AmendmentDetailsRequest::getAmendmentId,HashMap::new,Collectors.toCollection(ArrayList::new)));
// amendmentFormFields.forEach(data->{
// ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestMap.get(data.getAmendmentId());
// if (data.getFieldId().contains("amend_")){
// updateAmendmentDocument(applicationAmendmentRequestEntity, data);
// }
// });
applicationAmendmentRequestEntities.forEach(applicationAmendmentRequestEntity->{
ApplicationAmendmentRequestEntity oldEntity = Utils.getClonedEntityForData(applicationAmendmentRequestEntity);
updateAmendment(applicationAmendmentRequestEntity, amendmentFormFieldsMap.get(applicationAmendmentRequestEntity.getId()));
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().actionType(VersionActionTypeEnum.UPDATE).oldData(oldEntity).newData(applicationAmendmentRequestEntity).build());
});
applicationAmendmentRequestRepository.saveAll(applicationAmendmentRequestEntities);
// for (ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity : applicationAmendmentRequestEntities) {
// // Process form fields if present
// if (applicationAmendmentRequestEntity.getFormFields() != null) {
// // Parse existing form fields from JSON
// List<AmendmentFormFieldRequest> existingFormFields =
// Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getFormFields(), AmendmentFormFieldRequest.class);
//
// // Prepare a new list to hold updated form fields
// List<AmendmentFormFieldRequest> updatedFormFields = new ArrayList<>();
//
// // Map amendment details for quick lookup by amendment ID
// Map<Long, Object> amendmentDetailsMap = amendmentFormFields.stream()
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
// .filter(details -> details.getFieldValue() != null) // Null check for getFormFieldDocuments
// .collect(Collectors.toMap(
// AmendmentDetailsRequest::getAmendmentId,
// AmendmentDetailsRequest::getFieldValue
// ));
// // Get corresponding amendment documents for the current entity
// List<AmendmentFormFieldRequest> amendmentDocuments = (List<AmendmentFormFieldRequest>) amendmentDetailsMap.get(applicationAmendmentRequestEntity.getId());
// if (amendmentDocuments != null) {
// // Update existing form fields with new values
// for (AmendmentFormFieldRequest existingField : existingFormFields) {
// for (AmendmentFormFieldRequest newField : amendmentDocuments) {
// if (existingField.getFieldId().equals(newField.getFieldId())) {
// // Update fields if there are changes
// Utils.setIfUpdated(existingField::getValid, existingField::setValid, newField.getValid());
// Utils.setIfUpdated(existingField::getFieldValue, existingField::setFieldValue, newField.getFieldValue());
//
// updatedFormFields.add(existingField);
// break; // Move to the next existing field
// }
// }
// }
//
// // Convert updated form fields back to JSON and save to the database
// applicationAmendmentRequestEntity.setFormFields(Utils.convertListToJsonString(updatedFormFields));
// applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
// }
// }
//
// // Process amendment documents if present
// if (applicationAmendmentRequestEntity.getAmendmentDocument() != null) {
// String existingDocumentIds = applicationAmendmentRequestEntity.getAmendmentDocument();
//
// // Split comma-separated document IDs into a list
// List<String> existingDocumentIdList = Arrays.stream(existingDocumentIds.split(","))
// .map(String::trim)
// .filter(id -> !id.isEmpty())
// .collect(Collectors.toList());
//
// List<String> updatedDocumentIdList = new ArrayList<>();
// Map<Long, Object> amendmentDetailsMap = amendmentFormFields.stream()
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
// .collect(Collectors.toMap(
// AmendmentDetailsRequest::getAmendmentId,
// AmendmentDetailsRequest::getFieldValue
// ));
//
// String amendmentDocumentIds = (String) amendmentDetailsMap.get(applicationAmendmentRequestEntity.getId());
// if (amendmentDocumentIds != null) {
// // Split and validate new document IDs
// List<String> newDocumentIdList = Arrays.stream(amendmentDocumentIds.split(","))
// .map(String::trim)
// .filter(id -> !id.isEmpty())
// .collect(Collectors.toList());
//
// for (String existingId : existingDocumentIdList) {
// for (String newId : newDocumentIdList) {
// if (existingId.equals(newId)) {
// Optional<DocumentEntity> documentEntity = documentRepository.findByIdAndNotDeleted(Long.valueOf(newId));
// if(documentEntity.isPresent()) {
// updatedDocumentIdList.add(newId);
// break;
// }
// }
// }
// }
//
// // Add any new IDs not in the existing list
// for (String newId : newDocumentIdList) {
// if (!existingDocumentIdList.contains(newId)) {
// Optional<DocumentEntity> documentEntity = documentRepository.findByIdAndNotDeleted(Long.valueOf(newId));
// if(documentEntity.isPresent()) {
// updatedDocumentIdList.add(newId);
// }
// }
// }
// String updatedDocumentIds = String.join(",", updatedDocumentIdList);
//
// // Create the AmendmentDetailsResponseBean for structured data
// AmendmentDetailsResponseBean amendmentDetails = new AmendmentDetailsResponseBean();
// amendmentDetails.setAmendmentDocuments(updatedDocumentIds);
// AmendmentDetailsRequest amendmentDetailsRequest = amendmentFormFields.stream()
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
// .findFirst()
// .orElse(null);
//
// if (amendmentDetailsRequest != null) {
// amendmentDetails.setValid(amendmentDetailsRequest.getValid());
// } else {
// amendmentDetails.setValid(false);
// }
// String amendmentDetailsJson = Utils.convertListToJsonString(Collections.singletonList(amendmentDetails));
// applicationAmendmentRequestEntity.setAmendmentDocument(amendmentDetailsJson);
// applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
// }
// }
// }
}
private void updateAmendment(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity, List<AmendmentDetailsRequest> amendmentDetailsRequestList) {
if (CollectionUtils.isEmpty(amendmentDetailsRequestList)) {
return;
}
Map<String, AmendmentFormField> formFieldsMap = null;
List<AmendmentFormField> formFieldList = Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getFormFields(), AmendmentFormField.class);
if(Boolean.FALSE.equals(CollectionUtils.isEmpty(formFieldList))){
formFieldsMap = formFieldList.stream().collect(Collectors.toMap(AmendmentFormField::getFieldId, Function.identity()));
}
updateAmendmentData(applicationAmendmentRequestEntity, amendmentDetailsRequestList, formFieldsMap);
}
private static void updateAmendmentData(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity, List<AmendmentDetailsRequest> amendmentDetailsRequestList, Map<String, AmendmentFormField> formFieldsMap) {
amendmentDetailsRequestList.forEach(amendmentDetailsRequest -> {
if (amendmentDetailsRequest.getFieldId().contains("amend_")) {
AmendmentDetailsResponseBean amendmentDetails = Utils.convertStringToObject(applicationAmendmentRequestEntity.getAmendmentDocument(), AmendmentDetailsResponseBean.class);
if(amendmentDetails!=null) {
amendmentDetails.setValid(amendmentDetailsRequest.getValid());
applicationAmendmentRequestEntity.setAmendmentDocument(Utils.convertObjectToString(amendmentDetails));
}
} else if(Boolean.FALSE.equals(CollectionUtils.isEmpty(formFieldsMap))){
AmendmentFormField amendmentFormField = formFieldsMap.get(amendmentDetailsRequest.getFieldId());
amendmentFormField.setValid(amendmentDetailsRequest.getValid());
}
});
applicationAmendmentRequestEntity.setFormFields(Utils.convertListToJsonString(formFieldsMap.values().stream().toList()));
}
// private void updateAmendmentDocuments(List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities, List<AmendmentDetailsRequest> amendmentFormFields) {
// for (ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity : applicationAmendmentRequestEntities) {
// // Skip if there are no amendment documents
// if (applicationAmendmentRequestEntity.getAmendmentDocument() == null) {
// continue;
// }
//
// // Parse existing amendment fields from JSON
// List<AmendmentFieldRequest> existingAmendmentFields =
// Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getAmendmentDocument(), AmendmentFieldRequest.class);
//
// // Prepare a new list to hold updated amendment fields
// List<AmendmentFieldRequest> updatedAmendmentFields = new ArrayList<>();
//
// // Map amendment details for quick lookup by amendment ID
// Map<Long, List<AmendmentFieldRequest>> amendmentDetailsMap = amendmentFormFields.stream()
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
// .collect(Collectors.toMap(AmendmentDetailsRequest::getAmendmentId, AmendmentDetailsRequest::getAmendmentDocuments));
//
// // Get corresponding amendment documents for the current entity
// List<AmendmentFieldRequest> amendmentDocuments = amendmentDetailsMap.get(applicationAmendmentRequestEntity.getId());
// if (amendmentDocuments == null) {
// continue;
// }
//
// // Update existing amendment fields with new values
// for (AmendmentFieldRequest existingField : existingAmendmentFields) {
// for (AmendmentFieldRequest newField : amendmentDocuments) {
// if (existingField.getFieldId().equals(newField.getFieldId())) {
// // Update fields if there are changes
// Utils.setIfUpdated(existingField::getIsValid, existingField::setIsValid, newField.getIsValid());
// Utils.setIfUpdated(existingField::getFileValue, existingField::setFileValue, newField.getFileValue());
// Utils.setIfUpdated(existingField::getNameValue, existingField::setNameValue, newField.getNameValue());
//
// updatedAmendmentFields.add(existingField);
// break; // Move to the next existing field
// }
// }
// }
//
// // Convert updated fields back to JSON and save to the database
// applicationAmendmentRequestEntity.setAmendmentDocument(Utils.convertListToJsonString(updatedAmendmentFields));
// applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
// }
// }
private List<CriteriaRequest> processCriteria(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) {
List<CriteriaRequest> incomingCriteriaList = Optional.ofNullable(req.getCriteria()).orElse(new ArrayList<>());
List<CriteriaResponse> existingCriteriaList = entity.getCriteria() != null ?
Utils.convertJsonToList(entity.getCriteria(), new TypeReference<List<CriteriaResponse>>() {}) :
new ArrayList<>();
Map<Long, CriteriaResponse> existingCriteriaMap = existingCriteriaList.stream()
.collect(Collectors.toMap(CriteriaResponse::getId, criteria -> criteria));
List<CriteriaRequest> updatedCriteriaList = incomingCriteriaList.stream().map(incoming -> {
CriteriaRequest request = new CriteriaRequest();
request.setId(incoming.getId());
request.setScore(incoming.getScore());
request.setValid(incoming.getValid());
CriteriaResponse existingCriteria = existingCriteriaMap.get(incoming.getId());
if (existingCriteria != null) {
request.setScore(incoming.getScore() != null ? incoming.getScore() : existingCriteria.getScore());
request.setValid(incoming.getValid() != null ? incoming.getValid() : existingCriteria.getValid());
}
return request;
}).collect(Collectors.toList());
List<CriteriaRequest> missingCriteriaRequests = existingCriteriaList.stream()
.filter(existing -> !updatedCriteriaList.stream().map(CriteriaRequest::getId).toList().contains(existing.getId()))
.map(existing -> {
CriteriaRequest request = new CriteriaRequest();
request.setId(existing.getId());
request.setScore(existing.getScore());
request.setValid(existing.getValid());
return request;
}).toList();
updatedCriteriaList.addAll(missingCriteriaRequests);
return updatedCriteriaList;
}
private List<ChecklistRequest> processChecklist(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) {
List<ChecklistRequest> incomingChecklistList = Optional.ofNullable(req.getChecklist()).orElse(new ArrayList<>());
List<ChecklistResponse> existingChecklistList = entity.getChecklist() != null ?
Utils.convertJsonToList(entity.getChecklist(), new TypeReference<List<ChecklistResponse>>() {}) :
new ArrayList<>();
Map<Long, ChecklistResponse> existingChecklistMap = existingChecklistList.stream()
.collect(Collectors.toMap(ChecklistResponse::getId, checklist -> checklist));
List<ChecklistRequest> updatedChecklistList = incomingChecklistList.stream().map(incoming -> {
ChecklistRequest request = new ChecklistRequest();
request.setId(incoming.getId());
request.setValid(incoming.getValid());
ChecklistResponse existingChecklist = existingChecklistMap.get(incoming.getId());
if (existingChecklist != null && incoming.getValid() == null) {
request.setValid(existingChecklist.getValid());
}
return request;
}).collect(Collectors.toList());
List<ChecklistRequest> missingChecklistRequests = existingChecklistList.stream()
.filter(existing -> !updatedChecklistList.stream().map(ChecklistRequest::getId).toList().contains(existing.getId()))
.map(existing -> {
ChecklistRequest request = new ChecklistRequest();
request.setId(existing.getId());
request.setValid(existing.getValid());
return request;
}).toList();
updatedChecklistList.addAll(missingChecklistRequests);
return updatedChecklistList;
}
private List<FieldRequest> processField(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) {
List<FieldRequest> incomingFieldList = Optional.ofNullable(req.getFiles()).orElse(new ArrayList<>());
List<FieldResponse> existingFieldList = entity.getFile() != null ?
Utils.convertJsonToList(entity.getFile(), new TypeReference<List<FieldResponse>>() {}) :
new ArrayList<>();
Map<String, FieldResponse> existingFieldMap = existingFieldList.stream()
.collect(Collectors.toMap(FieldResponse::getId, field -> field));
List<FieldRequest> updatedFieldList = incomingFieldList.stream().map(incoming -> {
FieldRequest request = new FieldRequest();
request.setId(incoming.getId());
request.setValid(incoming.getValid());
FieldResponse existingField = existingFieldMap.get(incoming.getId());
if (existingField != null) {
request.setValid(incoming.getValid() != null ? incoming.getValid() : existingField.getValid());
}
return request;
}).collect(Collectors.toList());
List<FieldRequest> missingFieldRequests = existingFieldList.stream()
.filter(existing -> !updatedFieldList.stream().map(FieldRequest::getId).toList().contains(existing.getId()))
.map(existing -> {
FieldRequest request = new FieldRequest();
request.setId(existing.getId());
request.setValid(existing.getValid());
return request;
}).toList();
updatedFieldList.addAll(missingFieldRequests);
return updatedFieldList;
}
public ApplicationEvaluationEntity validateApplicationEvaluation(Long id) {
Optional<ApplicationEvaluationEntity> entityOptional = applicationEvaluationRepository.findByIdAndIsDeletedFalse(id);
if (entityOptional.isEmpty()) {
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_EVALUATION_NOT_FOUND, id));
}
return entityOptional.get();
}
public void validatePreinstructor(HttpServletRequest request,Long applicationId,Long assignedApplicationId){
if (applicationId == null && assignedApplicationId == null) {
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.EITHER_APPLICATION_OR_ASSIGNED_APPLICATION_ID_REQUIRED_MSG)
);
}
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
assignedApplicationsRepository.findByApplicationIdOrIdAndIsDeletedFalse(applicationId,assignedApplicationId);
if (assignedApplicationId != null) {
assignedApplicationsOptional = assignedApplicationsOptional.filter(a -> a.getId().equals(assignedApplicationId));
}
AssignedApplicationsEntity assignedApplications = assignedApplicationsOptional
.orElseThrow(() -> new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_WITH_ID_MSG)
));
if (applicationId == null) {
applicationId = assignedApplications.getApplication().getId();
}
validator.validatePreInstructor(request, assignedApplications.getUserId());
}
public ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(HttpServletRequest request, UserEntity user, Long applicationID, Long assignedApplicationID) {
Long applicationId;
Long assignedApplicationId;
validatePreinstructor(request, applicationID, assignedApplicationID);
if (applicationID == null && assignedApplicationID != null) {
assignedApplicationId = assignedApplicationID;
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId);
applicationId = assignedApplicationsOptional.map(a -> a.getApplication().getId()).orElse(null);
} else {
applicationId = applicationID;
if (assignedApplicationID == null && applicationID != null) {
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
assignedApplicationId = assignedApplicationsOptional.map(AssignedApplicationsEntity::getId).orElse(null);
} else {
assignedApplicationId = assignedApplicationID;
}
}
applicationService.validateApplication(applicationId);
Optional<ApplicationEvaluationEntity> entityOptional;
if (applicationId != null && assignedApplicationId != null) {
entityOptional = applicationEvaluationRepository.findByApplicationIdAndAssignedApplicationsEntity_IdAndIsDeletedFalse(applicationId, assignedApplicationId);
} else if (applicationId != null) {
entityOptional = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
} else if (assignedApplicationId != null) {
entityOptional = applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId);
} else {
entityOptional = applicationEvaluationRepository.findFirstByIsDeletedFalseOrderByCreatedDateDesc();
}
return entityOptional.map(this::convertToResponse)
.orElseGet(() -> {
return getEvaluationResponseByApplicationid(user, applicationId, assignedApplicationId);
});
}
private List<EvaluationDocumentRequest> prepareEvaluationDocumentBeanList(ApplicationEvaluationEntity entity) {
List<EvaluationDocumentRequest> docRequest = new ArrayList<>();
if (entity != null && entity.getEvaluationDocument() != null) {
docRequest = Utils.convertJsonToList(entity.getEvaluationDocument(), new TypeReference<List<EvaluationDocumentRequest>>() {});
}
return docRequest;
}
public ApplicationEvaluationResponse getEvaluationResponseByApplicationid(UserEntity user, Long applicationId, Long assignedApplicationId) {
ApplicationEvaluationEntity entity = new ApplicationEvaluationEntity();
ApplicationEvaluationResponse response = new ApplicationEvaluationResponse();
CallEntity call = null;
ApplicationEntity application = null;
AssignedApplicationsEntity assignedApplications = null;
if (applicationId != null && assignedApplicationId == null) {
application = applicationService.validateApplication(applicationId);
call = callRepository.findCallEntityByApplicationId(applicationId);
assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
} else if (assignedApplicationId != null) {
assignedApplications = assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_MSG)));
application = applicationService.validateApplication(assignedApplications.getApplication().getId());
call = callRepository.findCallEntityByApplicationId(application.getId());
} else {
call = callRepository.findCallEntityByApplicationId(applicationId);
assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
}
List<EvaluationCriteriaEntity> evaluationCriterias = evaluationCriteriaRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue());
List<CallTargetAudienceChecklistEntity> checklistEntities = callTargetAudienceChecklistRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue());
List<ApplicationFormEntity> applicationFormEntities = applicationFormRepository.findByApplicationId(applicationId);
response.setApplicationId(application.getId());
response.setAssignedApplicationId(assignedApplications.getId());
response.setEvaluationVersion(EvaluationVersionEnum.valueOf(application.getEvaluationVersion()));
response.setNote(null);
response.setMotivation(null);
response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(application.getStatus()));
response.setStatus(ApplicationEvaluationStatusTypeEnum.valueOf(ApplicationEvaluationStatusTypeEnum.OPEN.getValue()));
response.setMinScore(call.getThreshold()!=null?call.getThreshold():null);
response.setEvaluationEndDate(entity.getEndDate());
LocalDateTime callEndDate = application.getCall().getEndDate();
response.setCallEndDate(callEndDate);
response.setNumberOfCheck(call.getNumberOfCheck());
response.setAppointmentTemplateId(call.getAppointmentTemplateId());
setCriteriaResponses(entity, application.getId(), response, evaluationCriterias);
setChecklistResponses(entity, application.getId(), response, checklistEntities);
setFileResponses(entity, application.getId(), response, applicationFormEntities);
setApplicationDetails(response, application.getId(), user);
return response;
}
private void setCriteriaResponses(ApplicationEvaluationEntity entity, Long applicationId,
ApplicationEvaluationResponse response,
List<EvaluationCriteriaEntity> evaluationCriterias) {
List<CriteriaResponse> criteriaResponses = getInitialCriteriaResponses(entity, applicationId);
criteriaResponses.forEach(criteriaResponse -> {
EvaluationCriteriaEntity matchingEvaluationCriteria =
findMatchingEvaluationCriteria(criteriaResponse, evaluationCriterias);
if (matchingEvaluationCriteria != null) {
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationId);
Map<String, CriteriaMappedField> mappedFieldMap = populateMappedFields(
matchingEvaluationCriteria, applicationForms, applicationId);
criteriaResponse.setLabel(matchingEvaluationCriteria.getLookupData().getValue());
criteriaResponse.setMaxScore(matchingEvaluationCriteria.getScore());
criteriaResponse.setCriteriaMappedFields(new ArrayList<>(mappedFieldMap.values()));
}
});
response.setCriteria(criteriaResponses);
}
private List<CriteriaResponse> getInitialCriteriaResponses(ApplicationEvaluationEntity entity, Long applicationId) {
return entity.getCriteria() != null
? Utils.convertJsonToList(entity.getCriteria(), new TypeReference<List<CriteriaResponse>>() {})
: getCriteriaResponse(applicationId);
}
private EvaluationCriteriaEntity findMatchingEvaluationCriteria(CriteriaResponse criteriaResponse,
List<EvaluationCriteriaEntity> evaluationCriterias) {
return evaluationCriterias.stream()
.filter(evaluationCriteria -> evaluationCriteria.getId().equals(criteriaResponse.getId()))
.findFirst()
.orElse(null);
}
private Map<String, CriteriaMappedField> populateMappedFields(EvaluationCriteriaEntity matchingEvaluationCriteria,
List<ApplicationFormEntity> applicationForms,
Long applicationId) {
Map<String, CriteriaMappedField> mappedFieldMap = new HashMap<>();
List<CriteriaFormFieldEntity> criteriaFormFields = criteriaFormFieldRepository
.findByEvaluationCriteriaIdAndIsDeletedFalse(matchingEvaluationCriteria.getId());
for (ApplicationFormEntity applicationForm : applicationForms) {
for (CriteriaFormFieldEntity criteriaFormField : criteriaFormFields) {
String formFieldId = criteriaFormField.getFormFieldId();
if (!mappedFieldMap.containsKey(formFieldId)) {
// CriteriaMappedField mappedField = new CriteriaMappedField();
CriteriaMappedField mappedField = populateMappedField(formFieldId, criteriaFormField, applicationForm, applicationId);
if(mappedField != null) {
mappedFieldMap.put(formFieldId, mappedField);
}
}
}
}
return mappedFieldMap;
}
private CriteriaMappedField populateMappedField(String formFieldId,
CriteriaFormFieldEntity criteriaFormField,
ApplicationFormEntity applicationForm, Long applicationId) {
CriteriaMappedField mappedField = new CriteriaMappedField();
mappedField.setId(formFieldId);
if(Boolean.FALSE.equals(criteriaFormField.getFormId().equals(applicationForm.getForm().getId()))) {
return null;
}
formRepository.findById(criteriaFormField.getFormId()).ifPresent(formEntity -> {
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
contentResponseBeans.stream().filter(bean -> bean.getId().equals(formFieldId)).findFirst().ifPresent(contentResponseBean -> {
String label = getLabel(contentResponseBean);
mappedField.setFieldName(contentResponseBean.getName());
mappedField.setFieldLabel(label);
switch (contentResponseBean.getName()) {
case "fileupload":
populateFileDetailsAsFieldValue(mappedField, formFieldId, applicationForm, applicationId);
break;
case "checkboxes":
populateOptionFieldsAsFieldValue(mappedField, formFieldId, applicationForm, applicationId, contentResponseBean);
break;
case "paragraph":
handleParagraphField(applicationId, criteriaFormField, contentResponseBean, mappedField);
break;
case "table":
handleTableField(applicationId, criteriaFormField, contentResponseBean, mappedField);
break;
default:
populateOptionFieldsAsFieldValue(mappedField, formFieldId, applicationForm, applicationId, contentResponseBean);
}
});
});
return mappedField;
}
private void populateFileDetailsAsFieldValue(CriteriaMappedField mappedField, String formFieldId,
ApplicationFormEntity applicationForm, Long applicationId) {
applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
formFieldId, applicationForm.getId(), applicationId)
.ifPresent(formField -> {
if (formField.getFieldValue() != null) {
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
for (String docId : formField.getFieldValue().split(",")) {
Long documentId = Long.valueOf(docId.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
DocumentResponseBean responseBean = createDocumentResponseBean(documentEntity);
documentResponseBeans.add(responseBean);
});
}
// Set the list of DocumentResponseBean directly
mappedField.setFieldValue(documentResponseBeans);
}
});
}
private String getLabel(ContentResponseBean contentResponseBean) {
String label = contentResponseBean.getLabel();
if (contentResponseBean.getSettings() != null) {
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
if ("label".equals(setting.getName())) {
label = setting.getValue() != null ? setting.getValue().toString() : label;
break;
}
}
}
return label;
}
private void populateOptionFieldsAsFieldValue(CriteriaMappedField mappedField, String formFieldId, ApplicationFormEntity applicationForm, Long applicationId, ContentResponseBean contentBean) {
ObjectMapper objectMapper = new ObjectMapper();
findFormFieldValue(applicationId, formFieldId).ifPresent(formField -> {
Object value = formField.getFieldValue();
if (value == null) {
mappedField.setFieldValue(null);
return;
}
List<String> labels = new ArrayList<>();
if (value instanceof String) {
String fieldValue = (String) value;
if (fieldValue.contains(",")) {
try {
List<?> parsedValue = objectMapper.readValue(fieldValue, new TypeReference<List<?>>() {});
parsedValue.forEach(item -> addLabelToList(labels, item, contentBean));
} catch (JsonProcessingException e) {
String[] fallbackValues = fieldValue.split(",");
for (String item : fallbackValues) {
addLabelToList(labels, item.trim(), contentBean);
}
}
mappedField.setFieldValue(!labels.isEmpty() ? labels : null);
} else {
addLabelToList(labels, fieldValue.trim(), contentBean);
mappedField.setFieldValue(!labels.isEmpty() ? labels.get(0) : null);
}
} else if (value instanceof List<?>) {
List<?> parsedValue = (List<?>) value;
parsedValue.forEach(item -> addLabelToList(labels, item, contentBean));
mappedField.setFieldValue(!labels.isEmpty() ? labels : null);
}
});
}
private void addLabelToList(List<String> labels, Object item, ContentResponseBean contentBean) {
if (item instanceof String) {
Object label = PdfDao.findLabelInOptions(contentBean.getSettings(), item);
if (label != null) {
labels.add(label.toString());
}
}
}
public DocumentResponseBean createDocumentResponseBean(DocumentEntity documentEntity) {
DocumentResponseBean responseBean = new DocumentResponseBean();
responseBean.setId(documentEntity.getId());
responseBean.setName(documentEntity.getFileName());
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
responseBean.setSourceId(documentEntity.getSourceId());
responseBean.setFilePath(documentEntity.getFilePath());
responseBean.setCreatedDate(documentEntity.getCreatedDate());
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
return responseBean;
}
private void setChecklistResponses(ApplicationEvaluationEntity entity, Long applicationId, ApplicationEvaluationResponse response,
List<CallTargetAudienceChecklistEntity> checklistEntities) {
List<ChecklistResponse> checklistResponses = entity.getChecklist() != null ? Utils.convertJsonToList(entity.getChecklist(), new TypeReference<List<ChecklistResponse>>() {
}) : getChecklistResponse(applicationId);
checklistResponses.forEach(checklistResponse -> {
CallTargetAudienceChecklistEntity matchingChecklist = checklistEntities.stream().filter(checklistEntity -> checklistEntity.getId().equals(checklistResponse.getId()))
.findFirst().orElse(null);
if (matchingChecklist != null) {
checklistResponse.setLabel(matchingChecklist.getLookupData().getValue());
}
});
response.setChecklist(checklistResponses);
}
private void setFileResponses(ApplicationEvaluationEntity entity, Long applicationId, ApplicationEvaluationResponse response,
List<ApplicationFormEntity> applicationFormEntities) {
List<FieldResponse> fieldResponses = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference<List<FieldResponse>>() {
}) : getFieldResponses(applicationId);
Set<String> processedFieldIds = new HashSet<>();
fieldResponses.forEach(fieldResponse -> {
if (processedFieldIds.contains(fieldResponse.getId())) {
return;
}
applicationFormEntities.forEach(applicationForm -> {
FormEntity formEntity = applicationForm.getForm();
if (formEntity != null) {
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
contentResponseBeans.forEach(contentResponseBean -> {
if ("fileupload".equals(contentResponseBean.getName()) && contentResponseBean.getId().equals(fieldResponse.getId())) {
String label = null;
if (contentResponseBean.getSettings() != null) {
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
if ("label".equals(setting.getName())) {
label = setting.getValue() != null ? setting.getValue().toString() : label;
break;
}
}
}
fieldResponse.setLabel(label);
Optional<ApplicationFormFieldEntity> optionalFormField =
applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
fieldResponse.getId(), applicationForm.getId(), applicationId);
if (optionalFormField.isPresent() && optionalFormField.get().getFieldValue() != null) {
String[] documentIds = optionalFormField.get().getFieldValue().split(",");
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
for (String docId : documentIds) {
if (Boolean.FALSE.equals(docId.isEmpty())) {
Long documentId = Long.valueOf(docId.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
DocumentResponseBean responseBean = new DocumentResponseBean();
responseBean.setId(documentEntity.getId());
responseBean.setName(documentEntity.getFileName());
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
responseBean.setSourceId(documentEntity.getSourceId());
responseBean.setFilePath(documentEntity.getFilePath());
responseBean.setCreatedDate(documentEntity.getCreatedDate());
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
documentResponseBeans.add(responseBean);
});
}
}
fieldResponse.setFileDetail(documentResponseBeans);
}
processedFieldIds.add(fieldResponse.getId());
}
});
}
});
});
response.setFiles(fieldResponses);
}
private void setApplicationDetails(ApplicationEvaluationResponse response, Long applicationId, UserEntity user) {
ApplicationEntity application = applicationService.validateApplication(applicationId);
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository
.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
userService.validateUser(application.getUserId());
String firstName = user.getBeneficiary().getFirstName() != null ? user.getBeneficiary().getFirstName() : "";
String lastName = user.getBeneficiary().getLastName() != null ? user.getBeneficiary().getLastName() : "";
String beneficiary = String.join(" ", firstName, lastName).trim();
response.setBeneficiary(beneficiary);
response.setSubmissionDate(application.getSubmissionDate());
response.setNdg(application.getNdg() != null ? application.getNdg() : null);
response.setAppointmentId(application.getAppointmentId() != null ? application.getAppointmentId() : null);
response.setCallName(application.getCall().getName() != null ? application.getCall().getName() : null);
response.setProtocolNumber((application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null) ? application.getProtocol().getProtocolNumber() : null);
if (assignedApplications != null) {
response.setAssignedAt(assignedApplications.getAssignedAt());
}
if (application.getCompanyId() != null) {
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
response.setCompanyName(company.getCompanyName());
}
}
private Optional<ApplicationFormFieldEntity> findFormFieldValue(Long applicationId, String formFieldId) {
return applicationFormRepository.findByApplicationId(applicationId).stream()
.flatMap(applicationForm -> applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
formFieldId, applicationForm.getId(), applicationId).stream())
.findFirst();
}
List<CriteriaResponse> getCriteriaResponse(Long applicationId) {
CallEntity call = getCallEntityByApplicationId(applicationId);
List<EvaluationCriteriaEntity> evaluationCriterias = getEvaluationCriterias(call);
return evaluationCriterias.stream()
.map(criteria -> buildCriteriaResponse(applicationId, criteria))
.collect(Collectors.toList());
}
private CallEntity getCallEntityByApplicationId(Long applicationId) {
return callRepository.findCallEntityByApplicationId(applicationId);
}
private List<EvaluationCriteriaEntity> getEvaluationCriterias(CallEntity call) {
return evaluationCriteriaRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue());
}
private CriteriaResponse buildCriteriaResponse(Long applicationId, EvaluationCriteriaEntity criteria) {
CriteriaResponse response = new CriteriaResponse();
response.setId(criteria.getId());
response.setLabel(criteria.getLookupData().getValue());
response.setScore(null);
response.setMaxScore(criteria.getScore());
response.setValid(null);
List<CriteriaMappedField> mappedFields = getMappedFields(applicationId, criteria);
response.setCriteriaMappedFields(mappedFields);
return response;
}
private List<CriteriaMappedField> getMappedFields(Long applicationId, EvaluationCriteriaEntity criteria) {
List<CriteriaFormFieldEntity> criteriaFormFields = getCriteriaFormFields(criteria);
List<CriteriaMappedField> mappedFields = new ArrayList<>();
Set<String> processedFormFieldIds = new HashSet<>();
for (CriteriaFormFieldEntity criteriaFormField : criteriaFormFields) {
if (processedFormFieldIds.contains(criteriaFormField.getFormFieldId())) {
continue;
}
CriteriaMappedField mappedField = mapField(applicationId, criteriaFormField);
mappedFields.add(mappedField);
processedFormFieldIds.add(criteriaFormField.getFormFieldId());
}
return mappedFields;
}
private List<CriteriaFormFieldEntity> getCriteriaFormFields(EvaluationCriteriaEntity criteria) {
return criteriaFormFieldRepository.findByEvaluationCriteriaIdAndIsDeletedFalse(criteria.getId());
}
private CriteriaMappedField mapField(Long applicationId, CriteriaFormFieldEntity criteriaFormField) {
CriteriaMappedField mappedField = new CriteriaMappedField();
mappedField.setId(criteriaFormField.getFormFieldId());
FormEntity formEntity = formRepository.findById(criteriaFormField.getFormId()).orElse(null);
if (formEntity != null) {
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
contentResponseBeans.stream()
.filter(bean -> bean.getId().equals(criteriaFormField.getFormFieldId()))
.findFirst()
.ifPresent(contentResponseBean -> processFieldValue(applicationId, criteriaFormField, contentResponseBean, mappedField));
}
return mappedField;
}
private void processFieldValue(Long applicationId, CriteriaFormFieldEntity criteriaFormField, ContentResponseBean contentResponseBean, CriteriaMappedField mappedField) {
String label = getLabelFromSettings(contentResponseBean);
mappedField.setFieldLabel(label);
mappedField.setFieldName(contentResponseBean.getName());
boolean isCheckbox = "checkboxes".equals(contentResponseBean.getName());
boolean isFileUpload = "fileupload".equals(contentResponseBean.getName());
boolean isParagraph = "paragraph".equals(contentResponseBean.getName());
boolean isTable = "table".equals(contentResponseBean.getName());
if (isFileUpload) {
handleFileUpload(applicationId, criteriaFormField, mappedField);
} else if (isCheckbox) {
handleCheckbox(applicationId, criteriaFormField, contentResponseBean, mappedField);
}
else if (isParagraph) {
handleParagraphField(applicationId, criteriaFormField, contentResponseBean, mappedField);
} else if (isTable) {
handleTableField(applicationId, criteriaFormField, contentResponseBean, mappedField);
}
else {
handleOtherFields(applicationId, criteriaFormField, contentResponseBean, mappedField);
}
}
private void handleTableField(Long applicationId, CriteriaFormFieldEntity criteriaFormField,
ContentResponseBean contentResponseBean, CriteriaMappedField mappedField) {
Map<String, String> stateFieldMap = new HashMap<>();
Map<String, Boolean> stateFieldBoolean = new HashMap<>();
contentResponseBean.getSettings().stream()
.filter(setting -> "table_columns".equals(setting.getName()))
.map(SettingResponseBean::getValue)
.filter(Objects::nonNull)
.filter(settingValue -> settingValue instanceof Map)
.map(settingValue -> (Map<String, Object>) settingValue)
.map(valueMap -> (List<Map<String, Object>>) valueMap.get("stateFieldData"))
.filter(Objects::nonNull)
.flatMap(List::stream)
.forEach(fieldData -> {
String fieldName = (String) fieldData.get("name");
String fieldLabel = (String) fieldData.get("label");
Boolean predefined = (Boolean) fieldData.getOrDefault("predefined", false);
if (fieldName != null) {
stateFieldMap.put(fieldName, fieldLabel);
stateFieldBoolean.put(fieldName, predefined);
}
});
findFormFieldValue(applicationId, criteriaFormField.getFormFieldId()).ifPresent(formField -> {
String fieldValue1 = formField.getFieldValue();
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Map<String, String>> rowsData = objectMapper.readValue(fieldValue1, new TypeReference<List<Map<String, String>>>() {});
List<Map<String, Object>> tableData = new ArrayList<>();
for (Map<String, String> rowData : rowsData) {
Map<String, Object> mappedRow = new HashMap<>();
rowData.forEach((fieldKey, fieldValue) -> {
String columnLabel = stateFieldMap.getOrDefault(fieldKey, fieldKey);
mappedRow.put(columnLabel, fieldValue);
});
tableData.add(mappedRow);
}
mappedField.setFieldValue(tableData);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private void handleParagraphField(Long applicationId, CriteriaFormFieldEntity criteriaFormField, ContentResponseBean contentResponseBean, CriteriaMappedField mappedField) {
findFormFieldValue(applicationId, criteriaFormField.getFormFieldId()).ifPresent(formField -> {
String paragraph = contentResponseBean.getSettings().stream()
.filter(setting -> "text".equals(setting.getName()))
.map(SettingResponseBean::getValue)
.map(Object::toString)
.findFirst()
.orElse(null);
if (paragraph != null) {
mappedField.setFieldValue(paragraph.trim());
}
});
}
private String getLabelFromSettings(ContentResponseBean contentResponseBean) {
String label = contentResponseBean.getLabel();
if (contentResponseBean.getSettings() != null) {
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
if ("label".equals(setting.getName())) {
label = setting.getValue() != null ? setting.getValue().toString() : label;
break;
}
}
}
return label;
}
private void handleFileUpload(Long applicationId, CriteriaFormFieldEntity criteriaFormField, CriteriaMappedField mappedField) {
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
findFormFieldValue(applicationId, criteriaFormField.getFormFieldId()).ifPresent(formField -> {
String fieldValue = formField.getFieldValue();
if (fieldValue != null && (Boolean.FALSE.equals(fieldValue.isEmpty()))) {
String[] fieldValues = fieldValue.split(",");
for (String value : fieldValues) {
Long documentId = Long.valueOf(value.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
DocumentResponseBean responseBean = mapDocumentEntityToResponse(documentEntity);
documentResponseBeans.add(responseBean);
});
}
}
mappedField.setFieldValue(!documentResponseBeans.isEmpty() ? documentResponseBeans : null);
});
}
private DocumentResponseBean mapDocumentEntityToResponse(DocumentEntity documentEntity) {
DocumentResponseBean responseBean = new DocumentResponseBean();
responseBean.setId(documentEntity.getId());
responseBean.setName(documentEntity.getFileName());
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
responseBean.setSourceId(documentEntity.getSourceId());
responseBean.setFilePath(documentEntity.getFilePath());
responseBean.setCreatedDate(documentEntity.getCreatedDate());
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
return responseBean;
}
private void handleCheckbox(Long applicationId, CriteriaFormFieldEntity criteriaFormField, ContentResponseBean contentResponseBean, CriteriaMappedField mappedField) {
ObjectMapper objectMapper = new ObjectMapper();
findFormFieldValue(applicationId, criteriaFormField.getFormFieldId()).ifPresent(formField -> {
Object value = formField.getFieldValue();
List<String> labels = new ArrayList<>();
if (value == null) {
mappedField.setFieldValue(null);
return;
}
if (value instanceof String) {
List<?> parsedValue = parseJsonValue((String) value, objectMapper);
addLabelsFromParsedValues(parsedValue, contentResponseBean, labels);
} else if (value instanceof List<?>) {
List<?> parsedValue = (List<?>) value;
addLabelsFromParsedValues(parsedValue, contentResponseBean, labels);
}
mappedField.setFieldValue(!labels.isEmpty() ? (labels.size() == 1 ? labels.get(0) : labels) : null);
});
}
private List<?> parseJsonValue(String value, ObjectMapper objectMapper) {
try {
return objectMapper.readValue(value, new TypeReference<List<?>>() {});
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private void addLabelsFromParsedValues(List<?> parsedValue, ContentResponseBean contentResponseBean, List<String> labels) {
for (Object item : parsedValue) {
if (item instanceof String) {
Object label = PdfDao.findLabelInOptions(contentResponseBean.getSettings(), item);
if (label != null) {
labels.add(label.toString());
}
}
}
}
private void handleOtherFields(Long applicationId, CriteriaFormFieldEntity criteriaFormField, ContentResponseBean contentResponseBean, CriteriaMappedField mappedField) {
findFormFieldValue(applicationId, criteriaFormField.getFormFieldId()).ifPresent(formField -> {
String fieldValue = formField.getFieldValue() != null ? formField.getFieldValue().trim() : null;
Object label = PdfDao.findLabelInOptions(contentResponseBean.getSettings(), fieldValue);
if (label != null) {
mappedField.setFieldValue(fieldValue != null && !fieldValue.isEmpty() && !fieldValue.contains(",")
? label.toString()
: Arrays.asList(label.toString()));
}
});
}
List<ChecklistResponse> getChecklistResponse(Long applicationId) {
CallEntity call = callRepository.findCallEntityByApplicationId(applicationId);
List<CallTargetAudienceChecklistEntity> checklistEntities = callTargetAudienceChecklistRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue());
List<ChecklistResponse> checklistResponses = checklistEntities.stream().map(checklist -> {
ChecklistResponse response = new ChecklistResponse();
response.setId(checklist.getId());
response.setLabel(checklist.getLookupData().getValue());
response.setValid(null);
return response;
}).collect(Collectors.toList());
return checklistResponses;
}
public List<FieldResponse> getFieldResponses(Long applicationId) {
List<ApplicationFormEntity> applicationFormEntities = applicationFormRepository.findByApplicationId(applicationId);
List<FieldResponse> fieldResponses = new ArrayList<>();
for (ApplicationFormEntity applicationForm : applicationFormEntities) {
FormEntity formEntity = applicationForm.getForm();
if (formEntity != null) {
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
for (ContentResponseBean contentResponseBean : contentResponseBeans) {
if ("fileupload".equals(contentResponseBean.getName())) {
String fieldId = contentResponseBean.getId();
Long applicationFormId = applicationForm.getId();
Optional<ApplicationFormFieldEntity> optionalFormField = applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
fieldId, applicationFormId, applicationId);
if (optionalFormField.isPresent()) {
ApplicationFormFieldEntity formField = optionalFormField.get();
if (formField.getFieldValue() != null &&(Boolean.FALSE.equals(formField.getFieldValue().isEmpty()))) {
FieldResponse fieldResponse = new FieldResponse();
fieldResponse.setId(fieldId);
String label = null;
if (contentResponseBean.getSettings() != null) {
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
if ("label".equals(setting.getName())) {
label = setting.getValue() != null ? setting.getValue().toString() : label;
break;
}
}
}
fieldResponse.setLabel(label);
fieldResponse.setValid(null);
String[] documentIds = formField.getFieldValue().split(",");
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
for (String docId : documentIds) {
if (Boolean.FALSE.equals(docId.isEmpty())){
Long documentId = Long.valueOf(docId.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
DocumentResponseBean responseBean = new DocumentResponseBean();
responseBean.setId(documentEntity.getId());
responseBean.setName(documentEntity.getFileName());
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
responseBean.setSourceId(documentEntity.getSourceId());
responseBean.setFilePath(documentEntity.getFilePath());
responseBean.setCreatedDate(documentEntity.getCreatedDate());
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
documentResponseBeans.add(responseBean);
});
}
}
fieldResponse.setFileDetail(documentResponseBeans);
fieldResponses.add(fieldResponse);
}
}
}
}
}
}
return fieldResponses;
}
public void deleteById(Long id) {
ApplicationEvaluationEntity applicationEvaluationEntity = validateApplicationEvaluation(id);
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(applicationEvaluationEntity);
applicationEvaluationEntity.setIsDeleted(true);
saveApplicationEvaluationEntity(applicationEvaluationEntity, oldApplicationEvaluation);
}
public ApplicationEvaluationEntity saveApplicationEvaluationEntity(ApplicationEvaluationEntity applicationEvaluationEntityData, ApplicationEvaluationEntity oldApplicationEvaluation) {
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationRepository.save(applicationEvaluationEntityData);
/** This code is responsible for adding a version history log for the "Delete Application Evaluation" operation. **/
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldApplicationEvaluation).newData(applicationEvaluationEntityData)
.build());
return applicationEvaluationEntity;
}
public ApplicationEvaluationResponse updateApplicationEvaluationStatus(ApplicationEntity application, AssignedApplicationsEntity assignedApplicationsEntity,
ApplicationStatusForEvaluation newStatus) {
Optional<ApplicationEvaluationEntity> existingEntityOptional = applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(
assignedApplicationsEntity.getId());
ApplicationEvaluationEntity entity;
if (existingEntityOptional.isPresent()) {
ApplicationEvaluationEntity existingEntity = existingEntityOptional.get();
// UserEntity userEntity = userService.validateUser(application.getUserId());
// callService.validatePublishedCall(application.getCall().getId(), userEntity.getHub().getId());
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(application);
application.setStatus(newStatus.getValue());
application = applicationRepository.save(application);
/** This code is responsible for adding a version history log for the "Update Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEntity).newData(application).build());
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(existingEntity);
AssignedApplicationsEntity oldAssignedApplication = Utils.getClonedEntityForData(assignedApplicationsEntity);
List<ApplicationAmendmentRequestEntity> amendmentRequest = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(existingEntity.getId(),List.of(ApplicationAmendmentRequestEnum.AWAITING.getValue(),ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue()));
if(amendmentRequest !=null && Boolean.FALSE.equals(amendmentRequest.isEmpty())){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_CANNOT_APPROVED_OR_REJECTED));
}
String statusType = application.getStatus();
if (application.getStatus().equals(ApplicationStatusTypeEnum.APPROVED.getValue()) || application.getStatus().equals(ApplicationStatusTypeEnum.REJECTED.getValue())) {
existingEntity.setStatus(ApplicationEvaluationStatusTypeEnum.CLOSE.getValue());
existingEntity.setClosingDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CLOSE.getValue());
}
if (existingEntity.getStartDate() != null && existingEntity.getClosingDate() != null) {
long activeDays = ChronoUnit.DAYS.between(existingEntity.getStartDate(), existingEntity.getClosingDate());
activeDays -= existingEntity.getSuspendedDays() != null ? existingEntity.getSuspendedDays() : 0;
existingEntity.setActiveDays(activeDays);
}
entity = applicationEvaluationRepository.save(existingEntity);
assignedApplicationsRepository.save(assignedApplicationsEntity);
if (application.getStatus().equals(ApplicationStatusTypeEnum.APPROVED.getValue()) || application.getStatus().equals(ApplicationStatusTypeEnum.REJECTED.getValue())) {
/** This code is responsible for adding a version history log for the "Update Application Evaluation" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluation).newData(entity).build());
/** This code is responsible for adding a version history log for the "Update Assigned Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplication).newData(assignedApplicationsEntity).build());
}
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.APPROVED.getValue())))) {
application.setDateAccepted(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application = applicationRepository.save(application);
// emailNotificationDao.sendAdmissibilityNotificationEmailForApprovedApplication(application);
}
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.REJECTED.getValue())))) {
application.setDateRejected(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application = applicationRepository.save(application);
emailNotificationDao.sendInadmissibilityEmailForRejectedApplication(application,existingEntity);
}
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_RESULT);
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_RESULT);
notificationDao.sendNotificationToInstructor(placeHolders,existingEntity,NotificationTypeEnum.EVALUATION_RESULT);
return convertToResponse(entity);
}
return null;
}
public ApplicationEvaluationEntity validateApplicationEvaluationByApplicationId(Long applicationId) {
return applicationEvaluationRepository
.findByApplicationIdAndIsDeletedFalse(applicationId)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_EVALUATION_NOT_FOUND)));
}
public ApplicationEvaluationResponse updateApplicationEvaluation(
Long assignedApplicationId,
List<EvaluationDocumentRequest> docRequest) {
Optional<ApplicationEvaluationEntity> entityOptional=applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId);
ApplicationEvaluationEntity applicationEvaluationEntity =null;
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(entityOptional.get());
applicationEvaluationEntity = entityOptional.get();
if (docRequest != null) {
List<EvaluationDocumentRequest> existingDocs = new ArrayList<>();
for (EvaluationDocumentRequest doc : docRequest) {
if (doc.getFileValue() != null) {
Long fileId = Long.valueOf(doc.getFileValue());
documentService.validateDocument(fileId);
existingDocs.add(doc);
}
}
String updatedEvaluationDocJson = Utils.convertObjectToJson(existingDocs);
applicationEvaluationEntity.setEvaluationDocument(updatedEvaluationDocJson);
}
ApplicationEvaluationEntity savedEntity = applicationEvaluationRepository.save(applicationEvaluationEntity);
/** This code is responsible for adding a version history log for the "Upload Document in Application Evaluation" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluation).newData(savedEntity).build());
return convertToResponse(savedEntity);
}
public ApplicationEvaluationFormResponse createApplicationEvaluation(HttpServletRequest request, ApplicationEvaluationFormRequestBean applicationEvaluationFormRequestBean, Long evaluationFormId, Long assignedApplicationId){
UserEntity user = validator.validateUser(request);
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsService.validateAssignedApplication(assignedApplicationId);
ApplicationEntity application = applicationService.validateApplication(assignedApplicationsEntity.getApplication().getId());
// Convert FormRequestBean to ApplicationEvaluationRequest
ApplicationEvaluationRequest req = convertToApplicationEvaluationRequest(applicationEvaluationFormRequestBean);
// Call the existing method to create or update evaluation
ApplicationEvaluationResponse evaluationResponse = createOrUpdateApplicationEvaluation(user, req, assignedApplicationId);
ApplicationEvaluationEntity entity = applicationEvaluationService.validateApplicationEvaluation(evaluationResponse.getId());
//Handling Application Evaluation form
EvaluationFormEntity evaluationFormEntity = evaluationFormService.validateEvaluationForm(evaluationFormId);
validateFormFields(applicationEvaluationFormRequestBean,evaluationFormEntity);
// formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity);
// ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationRepository.findByAssignedApplicationsId(assignedApplicationId);
validateFormFieldCustom(applicationEvaluationFormRequestBean.getFormFields(),entity,evaluationFormEntity);
ApplicationEvaluationFormEntity applicationEvaluationFormEntity = getApplicationEvaluationFormOrCreate(evaluationFormEntity,entity);
createOrUpdateMultipleFormFields(applicationEvaluationFormRequestBean.getFormFields(), applicationEvaluationFormEntity, evaluationFormEntity);
return processEvaluationForm(entity);
}
private ApplicationEvaluationFormEntity getApplicationEvaluationFormOrCreate(EvaluationFormEntity evaluationFormEntity, ApplicationEvaluationEntity applicationEvaluationEntity) {
ApplicationEvaluationFormEntity applicationEvaluationFormEntity = applicationEvaluationFormRepository.findByEvaluationIdAndEvaluationFormId(applicationEvaluationEntity.getId(), evaluationFormEntity.getId());
ApplicationEvaluationFormEntity oldApplicationEvaluationFormEntity = Utils.getClonedEntityForData(applicationEvaluationFormEntity);
if (applicationEvaluationFormEntity == null) {
applicationEvaluationFormEntity = createApplicationEvaluationFormEntity(applicationEvaluationEntity, evaluationFormEntity);
/** This code is responsible for adding a version history log for the "Create application evalaution form" operation. **/
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(oldApplicationEvaluationFormEntity).newData(applicationEvaluationFormEntity)
.build());
}
return applicationEvaluationFormEntity;
}
public ApplicationEvaluationFormEntity createApplicationEvaluationFormEntity(ApplicationEvaluationEntity applicationEvaluationEntity, EvaluationFormEntity evaluationFormEntity) {
ApplicationEvaluationFormEntity applicationEvaluationFormEntity = new ApplicationEvaluationFormEntity();
applicationEvaluationFormEntity.setApplicationId(applicationEvaluationEntity.getApplicationId());
applicationEvaluationFormEntity.setEvaluationForm(evaluationFormEntity);
applicationEvaluationFormEntity.setApplicationEvaluation(applicationEvaluationEntity);
applicationEvaluationFormEntity.setIsDeleted(false);
return saveApplicationEvaluationFormEntity(applicationEvaluationFormEntity);
}
public void validateFormFields(ApplicationEvaluationFormRequestBean request, EvaluationFormEntity evaluationFormEntity) {
List<ContentResponseBean> contentResponseBeans=evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(evaluationFormEntity).getContent();
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 ApplicationEvaluationFormEntity saveApplicationEvaluationFormEntity(ApplicationEvaluationFormEntity applicationEvaluationFormEntity) {
return applicationEvaluationFormRepository.save(applicationEvaluationFormEntity);
}
public List<ApplicationEvaluationFormFieldEntity> createOrUpdateMultipleFormFields(List<ApplicationFormFieldRequestBean> formFieldRequestBeans,
ApplicationEvaluationFormEntity applicationEvaluationFormEntity, EvaluationFormEntity evaluationFormEntity) {
FieldValidator fieldValidator = FieldValidator.create();
List<ApplicationEvaluationFormFieldEntity> existingFields = applicationEvaluationFormFieldRepository.findByApplicationEvaluationFormId(applicationEvaluationFormEntity.getId());
List<ApplicationEvaluationFormFieldEntity> applicationEvaluationFormFieldEntities= formFieldRequestBeans.stream().map(requestBean -> createOrUpdateApplicationEvaluationFormField(requestBean, applicationEvaluationFormEntity, existingFields, evaluationFormEntity,fieldValidator))
.collect(Collectors.toList());
fieldValidator.validate();
return applicationEvaluationFormFieldEntities;
}
public ApplicationEvaluationFormFieldEntity createOrUpdateApplicationEvaluationFormField(ApplicationFormFieldRequestBean applicationFormFieldRequestBean,
ApplicationEvaluationFormEntity applicationEvaluationFormEntity,
List<ApplicationEvaluationFormFieldEntity> applicationEvaluationFormFieldEntities,
EvaluationFormEntity evaluationFormEntity,FieldValidator fieldValidator){
ApplicationEvaluationFormFieldEntity applicationEvaluationFormFieldEntity = new ApplicationEvaluationFormFieldEntity();
validateFileUploadDocuments(applicationFormFieldRequestBean, evaluationFormEntity);
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
ApplicationEvaluationFormFieldEntity oldApplicationEvaluationFormFieldData = null;
if (applicationEvaluationFormFieldEntities == null || applicationEvaluationFormFieldEntities.isEmpty()) {
applicationEvaluationFormFieldEntity = new ApplicationEvaluationFormFieldEntity();
applicationEvaluationFormFieldEntity.setApplicationEvaluationForm(applicationEvaluationFormEntity);
applicationEvaluationFormFieldEntity.setIsDeleted(false);
}else{
for (ApplicationEvaluationFormFieldEntity existingFieldEntity : applicationEvaluationFormFieldEntities) {
if (existingFieldEntity.getFieldId().equals(applicationFormFieldRequestBean.getFieldId())) {
applicationEvaluationFormFieldEntity = existingFieldEntity;
oldApplicationEvaluationFormFieldData = Utils.getClonedEntityForData(existingFieldEntity);
actionType = VersionActionTypeEnum.UPDATE;
break;
} else {
applicationEvaluationFormFieldEntity.setApplicationEvaluationForm(applicationEvaluationFormEntity);
applicationEvaluationFormFieldEntity.setIsDeleted(Boolean.FALSE);
}
}
}
Utils.setIfUpdated(applicationEvaluationFormFieldEntity::getFieldId, applicationEvaluationFormFieldEntity::setFieldId, applicationFormFieldRequestBean.getFieldId());
List<ContentResponseBean> contentBeans = Utils.convertJsonStringToList(evaluationFormEntity.getContent(), ContentResponseBean.class);
calculationProcessForFormula(applicationEvaluationFormEntity,contentBeans,applicationFormFieldRequestBean,fieldValidator);
if (applicationFormFieldRequestBean.getFieldValue() != null) {
applicationEvaluationFormFieldEntity.setFieldValue(Utils.convertObjectToJsonString(applicationFormFieldRequestBean.getFieldValue()));
} else {
applicationEvaluationFormFieldEntity.setFieldValue(null);
}
ApplicationEvaluationFormFieldEntity savedEvaluationFormFieldEntity = applicationEvaluationFormFieldRepository.save(applicationEvaluationFormFieldEntity);
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplicationEvaluationFormFieldData).newData(savedEvaluationFormFieldEntity).build());
log.info("Version history logged for action: {}, Field ID: {}", actionType, applicationEvaluationFormFieldEntity.getFieldId());
return savedEvaluationFormFieldEntity;
}
private List<Long> validateFileUploadDocuments(ApplicationFormFieldRequestBean applicationFormFieldRequestBean, EvaluationFormEntity evaluationFormEntity) {
List<Long> documentIds=null;
List<ContentResponseBean> contentResponseBeans=evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(evaluationFormEntity).getContent();
for (ContentResponseBean contentResponseBean:contentResponseBeans){
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 = applicationDao.validateDocumentIds(documentId);
}
}
}
}
return documentIds;
}
private List<ApplicationEvaluationFormFieldReponseBean> createEvaluationFormFieldResponse(
List<ApplicationEvaluationFormFieldEntity> evaluationFormFieldEntities,
ApplicationEvaluationFormEntity applicationEvaluationFormEntity){
List<ApplicationEvaluationFormFieldReponseBean> evaluationFormFieldResponseBeans = new ArrayList<>();
List<ContentResponseBean> contentResponseBeans =evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(applicationEvaluationFormEntity.getEvaluationForm()).getContent();
for (ApplicationEvaluationFormFieldEntity applicationEvaluationFormFieldEntity : evaluationFormFieldEntities) {
Optional<ContentResponseBean> fileUploadContent = contentResponseBeans.stream()
.filter(contentResponseBean -> "fileupload".equals(contentResponseBean.getName()) &&
contentResponseBean.getId().equals(applicationEvaluationFormFieldEntity.getFieldId()))
.findFirst();
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
if (fileUploadContent.isPresent()) {
String documentId = applicationEvaluationFormFieldEntity.getFieldValue();
if (documentId != null && !documentId.isEmpty()) {
documentResponseBeans = Arrays.stream(documentId.split(","))
.map(String::trim)
.map(Long::parseLong)
.map(docId -> {
DocumentEntity documentEntity = documentService.validateDocument(docId);
// if (Boolean.FALSE.equals(DocumentSourceTypeEnum.APPLICATION.getValue().equals(documentEntity.getSource()))) {
// throw new CustomValidationException(Status.NOT_FOUND,Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
// }
return documentEntity;
})
.map(callDao::convertToDocumentResponseBean)
.collect(Collectors.toList());
}
}
ApplicationEvaluationFormFieldReponseBean responseBean = convertToEvaluationFormFieldResponseBean(
applicationEvaluationFormFieldEntity, applicationEvaluationFormEntity.getId());
if (!documentResponseBeans.isEmpty()) {
responseBean.setFieldValue(documentResponseBeans);
}
evaluationFormFieldResponseBeans.add(responseBean);
}
return evaluationFormFieldResponseBeans;
}
private ApplicationEvaluationFormFieldReponseBean convertToEvaluationFormFieldResponseBean(ApplicationEvaluationFormFieldEntity entity,Long applicationEvaluationFormId){
ApplicationEvaluationFormFieldReponseBean applicationEvaluationFormFieldReponseBean = new ApplicationEvaluationFormFieldReponseBean();
applicationEvaluationFormFieldReponseBean.setApplicationEvaluationFormId(applicationEvaluationFormId);
applicationEvaluationFormFieldReponseBean.setFieldId(entity.getFieldId());
if(entity.getFieldValue() != null) {
applicationEvaluationFormFieldReponseBean.setFieldValue(Utils.getFieldValueAsObject(entity.getFieldValue()));
}
applicationEvaluationFormFieldReponseBean.setId(entity.getId());
applicationEvaluationFormFieldReponseBean.setCreatedDate(entity.getCreatedDate());
applicationEvaluationFormFieldReponseBean.setUpdatedDate(entity.getUpdatedDate());
return applicationEvaluationFormFieldReponseBean;
}
private ApplicationEvaluationFormResponse convertToApplicationEvaluationResponseBean(ApplicationEvaluationResponse applicationEvaluationResponse){
ApplicationEvaluationFormResponse response = new ApplicationEvaluationFormResponse();
response.setId(applicationEvaluationResponse.getId());
response.setApplicationId(applicationEvaluationResponse.getApplicationId());
response.setNote(applicationEvaluationResponse.getNote());
response.setEvaluationVersion(applicationEvaluationResponse.getEvaluationVersion());
response.setCreatedDate(applicationEvaluationResponse.getCreatedDate());
response.setUpdatedDate(applicationEvaluationResponse.getUpdatedDate());
response.setApplicationStatus(applicationEvaluationResponse.getApplicationStatus());
response.setAssignedApplicationId(applicationEvaluationResponse.getAssignedApplicationId());
response.setMinScore(applicationEvaluationResponse.getMinScore());
response.setStatus(applicationEvaluationResponse.getStatus());
response.setFiles(applicationEvaluationResponse.getFiles());
response.setEvaluationDocument(applicationEvaluationResponse.getEvaluationDocument());
response.setAmendmentDetails(applicationEvaluationResponse.getAmendmentDetails());
response.setBeneficiary(applicationEvaluationResponse.getBeneficiary());
response.setAssignedUserId(applicationEvaluationResponse.getAssignedUserId());
response.setAssignedUserName(applicationEvaluationResponse.getAssignedUserName());
response.setProtocolNumber(applicationEvaluationResponse.getProtocolNumber());
response.setCallName(applicationEvaluationResponse.getCallName());
response.setMotivation(applicationEvaluationResponse.getMotivation());
response.setSubmissionDate(applicationEvaluationResponse.getSubmissionDate());
response.setEvaluationEndDate(applicationEvaluationResponse.getEvaluationEndDate());
response.setCallEndDate(applicationEvaluationResponse.getCallEndDate());
response.setCompanyName(applicationEvaluationResponse.getCompanyName());
response.setAssignedAt(applicationEvaluationResponse.getAssignedAt());
response.setNdg(applicationEvaluationResponse.getNdg());
response.setAppointmentId(applicationEvaluationResponse.getAppointmentId());
response.setAmountRequested(applicationEvaluationResponse.getAmountRequested());
response.setAmountAccepted(applicationEvaluationResponse.getAmountAccepted());
response.setDateAccepted(applicationEvaluationResponse.getDateAccepted());
response.setDateRejected(applicationEvaluationResponse.getDateRejected());
return response;
}
public ApplicationEvaluationFormResponse getApplicationEvaluationForm(HttpServletRequest request, Long applicationId, Long assignedApplicationId ){
if (applicationId == null && assignedApplicationId == null) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.EITHER_APPLICATION_ID_OR_ASSIGNED_APPLICATION_ID_MUST_BE_PROVIDED));
}
ApplicationEvaluationEntity evaluationEntity = applicationEvaluationRepository.findByApplicationIdAndAssignedApplicationId(applicationId, assignedApplicationId);
return (evaluationEntity != null) ? processEvaluationForm(evaluationEntity) : null;
}
private ApplicationEvaluationFormResponse processEvaluationForm(ApplicationEvaluationEntity evaluationEntity){
Object convertedResponse = convertToResponse(evaluationEntity);
ApplicationEvaluationFormResponse response = objectMapper.convertValue(convertedResponse, ApplicationEvaluationFormResponse.class);
EvaluationFormEntity evaluationFormEntity = evaluationFormRepository.findByCallIdAndIsDeletedFalse(evaluationEntity.getAssignedApplicationsEntity().getApplication().getCall().getId());
response.setNumberOfCheck(evaluationEntity.getAssignedApplicationsEntity().getApplication().getCall().getNumberOfCheck());
response.setAppointmentTemplateId(evaluationEntity.getAssignedApplicationsEntity().getApplication().getApplicationEvaluationId());
if (evaluationFormEntity != null) {
response.setApplicationEvaluationFormResponse(convertEvaluationFormToResponse(evaluationFormEntity, evaluationEntity));
}
return response;
}
private ApplicationEvaluationFormResponseBean convertEvaluationFormToResponse(EvaluationFormEntity evaluationForm, ApplicationEvaluationEntity applicationEvaluationEntity) {
ApplicationEvaluationFormResponseBean applicationEvaluationFormResponseBean = createEvaluationFormResponse(evaluationForm);
ApplicationEvaluationFormEntity applicationEvaluationFormEntity = applicationEvaluationFormRepository.findByEvaluationIdAndEvaluationFormId(applicationEvaluationEntity.getId(), evaluationForm.getId());
if(applicationEvaluationFormEntity!=null) {
List<ApplicationEvaluationFormFieldEntity> applicationEvaluationFormFieldEntities = applicationEvaluationFormFieldRepository.findByApplicationEvaluationFormId(applicationEvaluationFormEntity.getId());
List<ApplicationEvaluationFormFieldReponseBean> evaluationFormFieldResponseBeans = createEvaluationFormFieldResponse(applicationEvaluationFormFieldEntities, applicationEvaluationFormEntity);
applicationEvaluationFormResponseBean.setFormFields(evaluationFormFieldResponseBeans);
}
return applicationEvaluationFormResponseBean;
}
private ApplicationEvaluationFormResponseBean createEvaluationFormResponse(EvaluationFormEntity evaluationFormEntity) {
ApplicationEvaluationFormResponseBean evaluationFormResponseBean = new ApplicationEvaluationFormResponseBean();
evaluationFormResponseBean.setId(evaluationFormEntity.getId());
evaluationFormResponseBean.setLabel(evaluationFormEntity.getLabel());
evaluationFormResponseBean.setCallId(evaluationFormEntity.getCall().getId());
evaluationFormResponseBean.setContent(evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(evaluationFormEntity).getContent());
return evaluationFormResponseBean;
}
public ApplicationEvaluationVersionResponse getApplicationEvaluationVersion(HttpServletRequest request, Long applicationId){
log.info("Fetching application evaluation version with ID: {}", applicationId);
ApplicationEntity applicationEntity = applicationService.validateApplication(applicationId);
return buildApplicationEvaluationVersionResponse(applicationEntity);
}
private ApplicationEvaluationVersionResponse buildApplicationEvaluationVersionResponse(ApplicationEntity applicationEntity) {
ApplicationEvaluationVersionResponse response = new ApplicationEvaluationVersionResponse();
response.setApplicationId(applicationEntity.getId());
response.setCallId(applicationEntity.getCall().getId());
response.setCompanyId(applicationEntity.getCompanyId());
response.setEvaluationVersion(EvaluationVersionEnum.valueOf(applicationEntity.getEvaluationVersion()));
response.setEvaluationId(applicationEntity.getApplicationEvaluationId());
return response;
}
public static ApplicationEvaluationRequest convertToApplicationEvaluationRequest(ApplicationEvaluationFormRequestBean formRequestBean) {
ApplicationEvaluationRequest request = new ApplicationEvaluationRequest();
request.setFiles(formRequestBean.getFiles());
request.setEvaluationDocument(formRequestBean.getEvaluationDocument());
request.setAmendmentDetails(formRequestBean.getAmendmentDetails());
request.setNote(formRequestBean.getNote());
request.setApplicationStatus(formRequestBean.getApplicationStatus());
request.setMotivation(formRequestBean.getMotivation());
request.setAmountAccepted(formRequestBean.getAmountAccepted());
request.setCriteria(null);
request.setChecklist(null);
return request;
}
public void calculationProcessForFormula(ApplicationEvaluationFormEntity applicationFormEntity, List<ContentResponseBean> contentResponseBeans, ApplicationFormFieldRequestBean applicationFormFieldRequestBean,FieldValidator fieldValidator) {
List<String> formulaValue = new ArrayList<>();
String formulaValueOpt=null;
String label=null;
for (ContentResponseBean contentResponseBean:contentResponseBeans){
if(contentResponseBean.getId().equals(applicationFormFieldRequestBean.getFieldId())){
for (SettingResponseBean settingResponseBean:contentResponseBean.getSettings()){
if (settingResponseBean.getName().equals(GepafinConstant.LABEL)){
label= String.valueOf(settingResponseBean.getValue());
}
if(settingResponseBean.getName().equals(GepafinConstant.FORMULA)){
String value= (String) settingResponseBean.getValue();
formulaValueOpt=value;
formulaValue=Utils.extractValues(value);
}
}
}
}
Map<String, String> mappedFormulaValue = new HashMap<>();
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
if (formulaValueOpt != null && fieldValue==null) {
fieldValue=0;
}
for (ContentResponseBean contentResponseBean : contentResponseBeans) {
String contentId = contentResponseBean.getId();
// Extract variable values once per contentResponseBean to avoid repeated stream operations
Set<String> variableValues = contentResponseBean.getSettings().stream()
.filter(setting -> GepafinConstant.VARIABLE.equals(setting.getName()))
.flatMap(setting -> {
Object value = setting.getValue(); // Get the raw value
if (value instanceof String) {
return Stream.of((String) value); // Handle single String case
} else if (value instanceof List) {
return ((List<?>) value).stream()
.filter(item -> item instanceof String) // Ensure it's a String
.map(item -> (String) item); // Convert to String
} else {
return Stream.empty(); // Ignore unexpected types
}
})
.collect(Collectors.toSet()); // Collect into a Set for uniqueness
for (String formula : formulaValue) {
if (variableValues.contains(formula)) { // O(1) lookup instead of O(n)
mappedFormulaValue.put(formula, contentId);
}
}
}
Map<String, String> updatedMappedFormulaValue = new HashMap<>();
for (Map.Entry<String, String> entry : mappedFormulaValue.entrySet()) {
String variable = entry.getKey();
String contentId = entry.getValue();
// Repository call using contentId
Optional<ApplicationEvaluationFormFieldEntity> optionalEntity = applicationEvaluationFormFieldRepository.findByApplicationEvaluationFormIdAndFieldIdAndIsDeletedFalse(applicationFormEntity.getId(),contentId);
// If entity is found, extract fieldValue and fieldId
optionalEntity.ifPresent(entity -> {
String entityFieldValue = entity.getFieldValue(); // Assuming getter method exists
String fieldId = entity.getFieldId(); // Assuming getter method exists
String tableType = contentResponseBeans.stream()
.filter(content -> content.getId().equals(fieldId)) // Match Content ID with fieldId
.flatMap(content -> content.getSettings().stream()) // Extract settings
.filter(setting -> GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(setting.getName())) // Match name
.map(setting -> setting.getName()) // Return the name of the setting
.findFirst() // Get the first match
.orElse(null); // Default to null if no match
if(tableType!=null){
JSONObject jsonObject = new JSONObject(entityFieldValue);
// Extract the value of total
entityFieldValue = jsonObject.getString(GepafinConstant.TOTAL);
}
updatedMappedFormulaValue.put(fieldId, entityFieldValue);
});
}
if(formulaValueOpt==null || formulaValueOpt.isEmpty()){
return;
}
double finalValue = applicationDao.evaluateFormula(formulaValueOpt, mappedFormulaValue, updatedMappedFormulaValue);
fieldValidator.formulaValidation(fieldValue, finalValue, label);
}
public void validateFormFieldCustom(List<ApplicationFormFieldRequestBean> applicationFormFieldRequestList, ApplicationEvaluationEntity applicationEvaluationEntity, EvaluationFormEntity evaluationFormEntity) {
Map<String, Object> formFieldMap = new LinkedHashMap<String, Object>();
for(ApplicationFormFieldRequestBean applicationFormFieldRequestBean:applicationFormFieldRequestList) {
if(applicationFormFieldRequestBean.getFieldValue()==null )
continue;
if (applicationFormFieldRequestBean.getFieldValue() != null ) {
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
// formDao.checkObjectData(applicationFormFieldRequestBean.getFieldId(), fieldValue, 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) {
formDao.setFormFieldMap(applicationFormFieldRequestBean.getFieldId(), formFieldMap, value);
}
}else if (list.stream().allMatch(item -> item instanceof Map<?, ?> map &&
map.keySet().stream().allMatch(String.class::isInstance))) {
if (fieldValue != null) {
formFieldMap.put(applicationFormFieldRequestBean.getFieldId(), fieldValue);
}
} else formDao.setFormFieldMap(applicationFormFieldRequestBean.getFieldId(), formFieldMap, fieldValue);
}
else {
formDao.setFormFieldMap(applicationFormFieldRequestBean.getFieldId(), formFieldMap, fieldValue);
}
}}
EvaluationFormResponseBean evaluationFormResponseBean = evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(evaluationFormEntity);
ApplicationEvaluationFormEntity applicationEvaluationForm=applicationEvaluationFormRepository.findByEvaluationIdAndEvaluationFormId(applicationEvaluationEntity.getId(),evaluationFormEntity.getId());
Boolean isApplicationFormExist= getApplicationEvaluationFormExist(applicationEvaluationForm);
FieldValidator validator = FieldValidator.create();
evaluationFormResponseBean.getContent().forEach(contentResponseBean -> {
String fieldId = contentResponseBean.getId();
String fieldLabel=contentResponseBean.getLabel();
Object object=formFieldMap.get(fieldId);
String value =Utils.convertToStringForFormFieldValue(object);
if(value == null && isApplicationFormExist) {
return;
}
FieldValidatorBean fieldValidatorBean = Utils.convertSourceObjectToDestinationObject(contentResponseBean.getValidators(), FieldValidatorBean.class);
validator
.minLength(value, fieldValidatorBean.getMinLength(), fieldLabel,fieldValidatorBean.getMin(),contentResponseBean) // Only applies if minLength is not null
.maxLength(value, fieldValidatorBean.getMaxLength(), fieldLabel,fieldValidatorBean.getMax(),contentResponseBean) // Only applies if maxLength is not null
.matchesPattern(value, fieldValidatorBean.getPattern(), fieldLabel) // Only applies if pattern is present
.validateCustom(value, fieldValidatorBean.getCustom(), fieldLabel,contentResponseBean); // Add the custom validation here
});
validator.validate();
}
private Boolean getApplicationEvaluationFormExist(ApplicationEvaluationFormEntity applicationEvaluationFormEntity) {
if(applicationEvaluationFormEntity !=null) {
return true;
}
return false;
}
}