package net.gepafin.tendermanagement.dao; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; 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.ApplicationService; import net.gepafin.tendermanagement.service.AssignedApplicationsService; import net.gepafin.tendermanagement.service.CallService; import net.gepafin.tendermanagement.service.UserService; import net.gepafin.tendermanagement.util.DateTimeUtil; import net.gepafin.tendermanagement.util.LoggingUtil; import net.gepafin.tendermanagement.util.Utils; import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException; import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException; import net.gepafin.tendermanagement.web.rest.api.errors.Status; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; import static net.gepafin.tendermanagement.util.Utils.setIfUpdated; import static org.apache.commons.lang3.StringUtils.isNumeric; @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; 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()); 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(30L); entity.setRemainingDays(30L); entity.setSuspendedDays(0L); entity.setStartDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now())); entity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now().plusDays(30))); 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 evaluationCriterias = evaluationCriteriaRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue()); List checklistEntities = callTargetAudienceChecklistRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue()); List applicationFormEntities = applicationFormRepository.findByApplicationId(entity.getApplicationId()); setCriteriaResponses(entity, response, evaluationCriterias); setChecklistResponses(entity, response, checklistEntities); setFieldResponses(entity, response, applicationFormEntities); setApplicationDetails(response, entity); return response; } 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.setEvaluationEndDate(entity.getEndDate()); response.setCreatedDate(entity.getCreatedDate()); response.setUpdatedDate(entity.getUpdatedDate()); } private void setCriteriaResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List evaluationCriterias) { List criteriaResponsesFromEntity = entity.getCriteria() != null ? Utils.convertJsonToList(entity.getCriteria(), new TypeReference>() { }) : new ArrayList<>(); List criteriaResponsesFromDB = getCriteriaResponse(entity.getApplicationId()); addMissingCriteriaResponses(criteriaResponsesFromEntity, criteriaResponsesFromDB, entity.getApplicationId()); criteriaResponsesFromEntity.forEach(criteriaResponse -> { EvaluationCriteriaEntity matchingEvaluationCriteria = evaluationCriterias.stream() .filter(evaluationCriteria -> evaluationCriteria.getId().equals(criteriaResponse.getId())).findFirst().orElse(null); if (matchingEvaluationCriteria != null) { criteriaResponse.setLabel(matchingEvaluationCriteria.getLookupData().getValue()); criteriaResponse.setMaxScore(matchingEvaluationCriteria.getScore()); List mappedFields = getMappedFieldsForCriteria(matchingEvaluationCriteria.getId(), entity.getApplicationId()); criteriaResponse.setCriteriaMappedFields(mappedFields); } }); response.setCriteria(criteriaResponsesFromEntity); } private void addMissingCriteriaResponses(List criteriaResponsesFromEntity, List criteriaResponsesFromDB, Long applicationId) { Set existingCriteriaIds = criteriaResponsesFromEntity.stream().map(CriteriaResponse::getId).collect(Collectors.toSet()); for (CriteriaResponse dbResponse : criteriaResponsesFromDB) { if (!existingCriteriaIds.contains(dbResponse.getId())) { List mappedFields = getMappedFieldsForCriteria(dbResponse.getId(), applicationId); dbResponse.setCriteriaMappedFields(mappedFields); criteriaResponsesFromEntity.add(dbResponse); } } } private List getMappedFieldsForCriteria(Long evaluationCriteriaId, Long applicationId) { List criteriaFormFields = criteriaFormFieldRepository.findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaId); List mappedFields = new ArrayList<>(); List applicationForms = applicationFormRepository.findByApplicationId(applicationId); for (ApplicationFormEntity applicationForm : applicationForms) { Set 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 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 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 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()); 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 checklistEntities) { List checklistResponsesFromEntity = entity.getChecklist() != null ? Utils.convertJsonToList(entity.getChecklist(), new TypeReference>() { }) : new ArrayList<>(); List checklistResponsesFromDB = getChecklistResponse(entity.getApplicationId()); addMissingChecklistResponses(checklistResponsesFromEntity, checklistResponsesFromDB); checklistResponsesFromEntity.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(checklistResponsesFromEntity); } private void addMissingChecklistResponses(List checklistResponsesFromEntity, List checklistResponsesFromDB) { Set 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 applicationFormEntities) { List fieldResponsesFromEntity = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference>() { }) : new ArrayList<>(); List fieldResponsesFromDB = getFieldResponses(entity.getApplicationId()); addMissingFieldResponses(fieldResponsesFromEntity, fieldResponsesFromDB); Set processedFieldIds = new HashSet<>(); fieldResponsesFromEntity.forEach(fieldResponse -> { if (processedFieldIds.contains(fieldResponse.getId())) { return; } applicationFormEntities.forEach(applicationForm -> { FormEntity formEntity = applicationForm.getForm(); if (formEntity != null) { // List contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class); List 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 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(","); List 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()); documentResponseBeans.add(responseBean); }); } } fieldResponse.setFileDetail(documentResponseBeans); } } processedFieldIds.add(fieldResponse.getId()); } }); } }); }); response.setFiles(fieldResponsesFromEntity); } private void addMissingFieldResponses(List fieldResponsesFromEntity, List fieldResponsesFromDB) { Set 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); UserEntity user = userService.validateUser(application.getUserId()); CallEntity call = callRepository.findCallEntityByApplicationId(entity.getApplicationId()); String firstName = user.getFirstName() != null ? user.getFirstName() : ""; String lastName = user.getLastName() != null ? user.getLastName() : ""; String beneficiary = String.join(" ", firstName, lastName).trim(); response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(application.getStatus())); response.setBeneficiary(beneficiary); 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); response.setSubmissionDate(application.getSubmissionDate() != null ? application.getSubmissionDate() : null); LocalDateTime callEndDate = application.getCall().getEndDate(); response.setCallEndDate(callEndDate); } public ApplicationEvaluationResponse createOrUpdateApplicationEvaluation( UserEntity user, ApplicationEvaluationRequest req, Long assignedApplicationId) { Optional existingEntityOptional = applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId); ApplicationEvaluationEntity entity = null; Optional assignedApplications = assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId); ApplicationEvaluationEntity oldApplicationEvaluation = null; VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT; if (existingEntityOptional.isPresent()) { entity = existingEntityOptional.get(); oldApplicationEvaluation = Utils.getClonedEntityForData(entity); entity.setCriteria(Utils.convertObjectToJson(filterNonNullCriteria(processCriteria(entity, req)))); entity.setChecklist(Utils.convertObjectToJson(filterNonNullChecklist(processChecklist(entity, req)))); entity.setFile(Utils.convertObjectToJson(filterNonNullFields(processField(entity, req)))); entity.setIsDeleted(false); setIfUpdated(entity::getNote, entity::setNote, req.getNote()); setIfUpdated(entity::getMotivation, entity::setMotivation, req.getMotivation()); actionType = VersionActionTypeEnum.UPDATE; } else { entity = convertToEntity(user, req, assignedApplicationId); actionType = VersionActionTypeEnum.INSERT; } ApplicationStatusForEvaluation status = req.getApplicationStatus(); ApplicationEvaluationEntity savedEntity = applicationEvaluationRepository.save(entity); /** 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()); if (status != null) { ApplicationEntity application = applicationService.validateApplication(assignedApplications.get().getApplication().getId()); AssignedApplicationsEntity assignedApplicationsEntity = assignedApplications.get(); return updateApplicationEvaluationStatus(application, assignedApplicationsEntity, status); } else { return convertToResponse(savedEntity); } } private List filterNonNullChecklist(List checklistRequests) { return checklistRequests.stream().filter(request -> request.getValid() != null).collect(Collectors.toList()); } private List filterNonNullCriteria(List criteriaRequests) { return criteriaRequests.stream().filter(request -> request.getScore() != null && request.getValid() != null).collect(Collectors.toList()); } private List filterNonNullFields(List fieldRequests) { return fieldRequests.stream().filter(request -> request.getValid() != null).collect(Collectors.toList()); } private List processCriteria(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) { List incomingCriteriaList = Optional.ofNullable(req.getCriteria()).orElse(new ArrayList<>()); List existingCriteriaList = entity.getCriteria() != null ? Utils.convertJsonToList(entity.getCriteria(), new TypeReference>() {}) : new ArrayList<>(); Map existingCriteriaMap = existingCriteriaList.stream() .collect(Collectors.toMap(CriteriaResponse::getId, criteria -> criteria)); List 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 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 processChecklist(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) { List incomingChecklistList = Optional.ofNullable(req.getChecklist()).orElse(new ArrayList<>()); List existingChecklistList = entity.getChecklist() != null ? Utils.convertJsonToList(entity.getChecklist(), new TypeReference>() {}) : new ArrayList<>(); Map existingChecklistMap = existingChecklistList.stream() .collect(Collectors.toMap(ChecklistResponse::getId, checklist -> checklist)); List 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 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 processField(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) { List incomingFieldList = Optional.ofNullable(req.getFiles()).orElse(new ArrayList<>()); List existingFieldList = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference>() {}) : new ArrayList<>(); Map existingFieldMap = existingFieldList.stream() .collect(Collectors.toMap(FieldResponse::getId, field -> field)); List 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 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 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 ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(UserEntity user, Long applicationId, Long assignedApplicationId) { applicationService.validateApplication(applicationId); Optional 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); }); } 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 evaluationCriterias = evaluationCriteriaRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue()); List checklistEntities = callTargetAudienceChecklistRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue()); List applicationFormEntities = applicationFormRepository.findByApplicationId(applicationId); response.setApplicationId(application.getId()); response.setAssignedApplicationId(assignedApplications.getId()); 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); 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 evaluationCriterias) { List criteriaResponses = getInitialCriteriaResponses(entity, applicationId); criteriaResponses.forEach(criteriaResponse -> { EvaluationCriteriaEntity matchingEvaluationCriteria = findMatchingEvaluationCriteria(criteriaResponse, evaluationCriterias); if (matchingEvaluationCriteria != null) { List applicationForms = applicationFormRepository.findByApplicationId(applicationId); Map 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 getInitialCriteriaResponses(ApplicationEvaluationEntity entity, Long applicationId) { return entity.getCriteria() != null ? Utils.convertJsonToList(entity.getCriteria(), new TypeReference>() {}) : getCriteriaResponse(applicationId); } private EvaluationCriteriaEntity findMatchingEvaluationCriteria(CriteriaResponse criteriaResponse, List evaluationCriterias) { return evaluationCriterias.stream() .filter(evaluationCriteria -> evaluationCriteria.getId().equals(criteriaResponse.getId())) .findFirst() .orElse(null); } private Map populateMappedFields(EvaluationCriteriaEntity matchingEvaluationCriteria, List applicationForms, Long applicationId) { Map mappedFieldMap = new HashMap<>(); List 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 contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class); List 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 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 labels = new ArrayList<>(); if (value instanceof String) { String fieldValue = (String) value; if (fieldValue.contains(",")) { try { List parsedValue = objectMapper.readValue(fieldValue, new TypeReference>() {}); 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 labels, Object item, ContentResponseBean contentBean) { if (item instanceof String) { Object label = PdfDao.findLabelInOptions(contentBean.getSettings(), item); if (label != null) { labels.add(label.toString()); } } } private 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()); return responseBean; } private void setChecklistResponses(ApplicationEvaluationEntity entity, Long applicationId, ApplicationEvaluationResponse response, List checklistEntities) { List checklistResponses = entity.getChecklist() != null ? Utils.convertJsonToList(entity.getChecklist(), new TypeReference>() { }) : 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 applicationFormEntities) { List fieldResponses = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference>() { }) : getFieldResponses(applicationId); Set processedFieldIds = new HashSet<>(); fieldResponses.forEach(fieldResponse -> { if (processedFieldIds.contains(fieldResponse.getId())) { return; } applicationFormEntities.forEach(applicationForm -> { FormEntity formEntity = applicationForm.getForm(); if (formEntity != null) { // List contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class); List 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 optionalFormField = applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId( fieldResponse.getId(), applicationForm.getId(), applicationId); if (optionalFormField.isPresent() && optionalFormField.get().getFieldValue() != null) { String[] documentIds = optionalFormField.get().getFieldValue().split(","); List 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()); 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); userService.validateUser(application.getUserId()); String firstName = user.getFirstName() != null ? user.getFirstName() : ""; String lastName = user.getLastName() != null ? user.getLastName() : ""; String beneficiary = String.join(" ", firstName, lastName).trim(); response.setBeneficiary(beneficiary); response.setCallName(application.getCall().getName() != null ? application.getCall().getName() : null); response.setProtocolNumber((application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null) ? application.getProtocol().getProtocolNumber() : null); response.setSubmissionDate(application.getSubmissionDate() != null ? application.getSubmissionDate() : null); } private Optional findFormFieldValue(Long applicationId, String formFieldId) { return applicationFormRepository.findByApplicationId(applicationId).stream() .flatMap(applicationForm -> applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId( formFieldId, applicationForm.getId(), applicationId).stream()) .findFirst(); } List getCriteriaResponse(Long applicationId) { CallEntity call = getCallEntityByApplicationId(applicationId); List 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 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 mappedFields = getMappedFields(applicationId, criteria); response.setCriteriaMappedFields(mappedFields); return response; } private List getMappedFields(Long applicationId, EvaluationCriteriaEntity criteria) { List criteriaFormFields = getCriteriaFormFields(criteria); List mappedFields = new ArrayList<>(); Set 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 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 contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class); List 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 stateFieldMap = new HashMap<>(); Map 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) settingValue) .map(valueMap -> (List>) 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> rowsData = objectMapper.readValue(fieldValue1, new TypeReference>>() {}); List> tableData = new ArrayList<>(); for (Map rowData : rowsData) { Map 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 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()); 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 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>() {}); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } private void addLabelsFromParsedValues(List parsedValue, ContentResponseBean contentResponseBean, List 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 getChecklistResponse(Long applicationId) { CallEntity call = callRepository.findCallEntityByApplicationId(applicationId); List checklistEntities = callTargetAudienceChecklistRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue()); List 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 getFieldResponses(Long applicationId) { List applicationFormEntities = applicationFormRepository.findByApplicationId(applicationId); List fieldResponses = new ArrayList<>(); for (ApplicationFormEntity applicationForm : applicationFormEntities) { FormEntity formEntity = applicationForm.getForm(); if (formEntity != null) { // List contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class); List contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent(); for (ContentResponseBean contentResponseBean : contentResponseBeans) { if ("fileupload".equals(contentResponseBean.getName())) { String fieldId = contentResponseBean.getId(); Long applicationFormId = applicationForm.getId(); Optional 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 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()); 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 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); String statusType = application.getStatus(); if (application.getStatus().equals(ApplicationStatusTypeEnum.APPROVED.getValue()) || application.getStatus().equals(ApplicationStatusTypeEnum.REJECTED.getValue())) { existingEntity.setStatus(ApplicationEvaluationStatusTypeEnum.CLOSE.getValue()); assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CLOSE.getValue()); } 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()); } List amendmentRequest = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(existingEntity.getId(),ApplicationAmendmentRequestEnum.AWAITING.getValue()); if(amendmentRequest !=null && Boolean.FALSE.equals(amendmentRequest.isEmpty())){ throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_CANNOT_APPROVED_OR_REJECTED)); } if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.APPROVED.getValue())))) { emailNotificationDao.sendAdmissibilityNotificationEmailForApprovedApplication(application); } if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.REJECTED.getValue())))) { emailNotificationDao.sendInadmissibilityEmailForRejectedApplication(application,existingEntity); } return convertToResponse(entity); } return null; } }