updated code for amendment api

This commit is contained in:
harish
2024-11-24 20:14:09 +05:30
parent 905a83698f
commit ac6c4ba0b0
8 changed files with 481 additions and 311 deletions

View File

@@ -12,6 +12,7 @@ import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum;
import net.gepafin.tendermanagement.enums.*;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.request.AmendmentFormField.AmendmentIsUploadedByEnum;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.*;
@@ -21,6 +22,8 @@ import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
@@ -29,6 +32,8 @@ import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.log;
@@ -218,10 +223,10 @@ public class ApplicationAmendmentRequestDao {
applicationAmendmentRequestEntity.setApplicationId(applicationId);
if (applicationAmendmentRequest.getFormFields() != null) {
List<ApplicationFormFieldRequestBean> formFieldRequestBean = applicationAmendmentRequest.getFormFields().stream()
List<AmendmentFormField> formFieldRequestBean = applicationAmendmentRequest.getFormFields().stream()
.filter(AmendmentFormFieldResponse::isSelected)
.map(amendmentFormFieldRequest -> {
ApplicationFormFieldRequestBean formField = new ApplicationFormFieldRequestBean();
AmendmentFormField formField = new AmendmentFormField();
formField.setFieldId(amendmentFormFieldRequest.getFieldId());
formField.setFieldValue(null);
return formField;
@@ -263,132 +268,134 @@ public class ApplicationAmendmentRequestDao {
}
public ApplicationAmendmentRequestResponse convertEntityToResponse(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity) {
ApplicationAmendmentRequestResponse applicationAmendmentRequestResponse = new ApplicationAmendmentRequestResponse();
applicationAmendmentRequestResponse.setId(applicationAmendmentRequestEntity.getId());
Long applicationId = applicationAmendmentRequestEntity.getApplicationId();
ApplicationAmendmentRequestResponse response = initializeBasicResponse(applicationAmendmentRequestEntity);
ApplicationEntity application = applicationService.validateApplication(applicationId);
applicationAmendmentRequestResponse.setApplicationId(applicationId);
applicationAmendmentRequestResponse.setCallEmail(application.getCall().getEmail());
applicationAmendmentRequestResponse.setApplicationEvaluationId(applicationAmendmentRequestEntity.getApplicationEvaluationEntity().getId());
applicationAmendmentRequestResponse.setNote(applicationAmendmentRequestEntity.getNote());
applicationAmendmentRequestResponse.setStatus(ApplicationAmendmentRequestEnum.valueOf(applicationAmendmentRequestEntity.getStatus()));
applicationAmendmentRequestResponse.setResponseDays(applicationAmendmentRequestEntity.getResponseDays());
applicationAmendmentRequestResponse.setInternalNote(applicationAmendmentRequestEntity.getInternalNote());
LocalDateTime startDate = applicationAmendmentRequestEntity.getStartDate();
applicationAmendmentRequestResponse.setStartDate(startDate);
List<ApplicationFormEntity> forms = applicationFormRepository.findByApplicationId(applicationAmendmentRequestEntity.getApplicationId());
Map<String, String> fieldIdToLabelMap = extractFieldIdToLabelMap(forms);
LocalDateTime expirationDate = startDate.plus(expirationDays, ChronoUnit.DAYS);
applicationAmendmentRequestResponse.setExpirationDate(expirationDate);
List<AmendmentFormField> amendmentFormFields = Utils.convertJsonStringToList(
applicationAmendmentRequestEntity.getFormFields(), AmendmentFormField.class);
Map<String, ApplicationFormFieldEntity> formFieldEntityMap = getApplicationFormFieldEntityMap(applicationAmendmentRequestEntity, amendmentFormFields);
applicationAmendmentRequestResponse.setIsSendEmail(applicationAmendmentRequestEntity.getIsEmail());
applicationAmendmentRequestResponse.setIsSendNotification(applicationAmendmentRequestEntity.getIsNotification());
String callName = application.getCall().getName();
Long protocolNumber = (applicationAmendmentRequestEntity.getProtocol() != null && applicationAmendmentRequestEntity.getProtocol().getProtocolNumber() != null)
? applicationAmendmentRequestEntity.getProtocol().getProtocolNumber()
: null;
UserEntity userEntity = userService.validateUser(application.getUserId());
String firstName = userEntity.getBeneficiary() != null ? userEntity.getBeneficiary().getFirstName() : "";
String lastName = userEntity.getBeneficiary() != null ? userEntity.getBeneficiary().getLastName() : "";
processFormFields(amendmentFormFields, fieldIdToLabelMap, formFieldEntityMap, response);
String beneficiaryName = (!firstName.isBlank() ? firstName : "") +
(!lastName.isBlank() ? " " + lastName : "");
beneficiaryName = beneficiaryName.isBlank() ? "" : beneficiaryName;
applicationAmendmentRequestResponse.setCallName(callName);
applicationAmendmentRequestResponse.setProtocolNumber(protocolNumber);
applicationAmendmentRequestResponse.setBeneficiaryName(beneficiaryName);
List<ApplicationFormEntity> forms = applicationFormRepository.findByApplicationId(applicationId);
List<AmendmentFormFieldResponse> allFormFields = new ArrayList<>();
for (ApplicationFormEntity form : forms) {
String content = form.getForm().getContent();
List<Map<String, Object>> result = filterByName(content, "fileupload");
allFormFields.addAll(getIdAndLabelFromResult(result));
}
Map<String, String> fieldIdToLabelMap = allFormFields.stream()
.collect(Collectors.toMap(AmendmentFormFieldResponse::getFieldId, AmendmentFormFieldResponse::getLabel));
String formFieldsJson = applicationAmendmentRequestEntity.getFormFields();
List<AmendmentFormFieldResponse> formFields = Utils.convertJsonToList(
formFieldsJson, new TypeReference<List<AmendmentFormFieldResponse>>() {
});
for (AmendmentFormFieldResponse formField : formFields) {
String label = fieldIdToLabelMap.get(formField.getFieldId());
formField.setLabel(label);
formField.setSelected(true);
}
// Set the filtered formFields in the response
applicationAmendmentRequestResponse.setFormFields(formFields);
String applicationFormFieldsJson = applicationAmendmentRequestEntity.getFormFields();
List<ApplicationFormFieldResponseBean> applicationFormFields = Utils.convertJsonToList(
formFieldsJson, new TypeReference<List<ApplicationFormFieldResponseBean>>() {
});
List<ApplicationFormFieldResponseBean> fileDetailResponses = new ArrayList<>();
for (ApplicationFormFieldResponseBean field : applicationFormFields) {
ApplicationFormFieldResponseBean responseBean = new ApplicationFormFieldResponseBean();
responseBean.setFieldId(field.getFieldId());
Optional<ApplicationFormFieldEntity> formFieldEntity = Optional.empty();
for (ApplicationFormEntity form : forms) {
formFieldEntity = applicationFormFieldRepository
.findByApplicationFormIdAndFieldId(form.getId(), field.getFieldId());
if (formFieldEntity.isPresent()) {
// Set the applicationFormId from the matching form
responseBean.setApplicationFormId(form.getId());
responseBean.setId(formFieldEntity.get().getId());
responseBean.setCreatedDate(formFieldEntity.get().getCreatedDate());
responseBean.setUpdatedDate(formFieldEntity.get().getUpdatedDate());
break;
}
}
// Check if fieldValue is not null and is a String
if (field.getFieldValue() instanceof String && field.getFieldValue() != null && !((String) field.getFieldValue()).isBlank()) {
String fieldValueString = (String) field.getFieldValue();
String[] documentIds = fieldValueString.split(",");
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
// Process each document ID
for (String docId : documentIds) {
try {
Long documentId = Long.valueOf(docId.trim());
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
DocumentResponseBean docBean = new DocumentResponseBean();
docBean.setId(documentEntity.getId());
docBean.setName(documentEntity.getFileName());
docBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
docBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
docBean.setSourceId(documentEntity.getSourceId());
docBean.setFilePath(documentEntity.getFilePath());
docBean.setCreatedDate(documentEntity.getCreatedDate());
docBean.setUpdatedDate(documentEntity.getUpdatedDate());
documentResponseBeans.add(docBean);
});
} catch (NumberFormatException e) {
// Handle the case where documentId is not a valid number
// Log the error if necessary
}
}
responseBean.setFieldValue(documentResponseBeans);
} else {
responseBean.setFieldValue(null);
}
fileDetailResponses.add(responseBean);
}
applicationAmendmentRequestResponse.setApplicationFormFields(fileDetailResponses);
return applicationAmendmentRequestResponse;
return response;
}
public ApplicationAmendmentRequestEntity validateApplicationAmendmentRequest(Long id) {
private ApplicationAmendmentRequestResponse initializeBasicResponse(ApplicationAmendmentRequestEntity entity) {
ApplicationAmendmentRequestResponse response = new ApplicationAmendmentRequestResponse();
response.setId(entity.getId());
response.setApplicationId(entity.getApplicationId());
response.setApplicationEvaluationId(entity.getApplicationEvaluationEntity().getId());
response.setNote(entity.getNote());
response.setStatus(ApplicationAmendmentRequestEnum.valueOf(entity.getStatus()));
response.setResponseDays(entity.getResponseDays());
response.setInternalNote(entity.getInternalNote());
LocalDateTime startDate = entity.getStartDate();
response.setStartDate(startDate);
response.setExpirationDate(startDate.plus(expirationDays, ChronoUnit.DAYS));
response.setIsSendEmail(entity.getIsEmail());
response.setIsSendNotification(entity.getIsNotification());
ApplicationEntity application = applicationService.validateApplication(entity.getApplicationId());
response.setCallEmail(application.getCall().getEmail());
response.setCallName(application.getCall().getName());
UserEntity userEntity = userService.validateUser(application.getUserId());
response.setBeneficiaryName(buildBeneficiaryName(userEntity));
Long protocolNumber = entity.getProtocol() != null ? entity.getProtocol().getProtocolNumber() : null;
response.setProtocolNumber(protocolNumber);
return response;
}
private Map<String, String> extractFieldIdToLabelMap(List<ApplicationFormEntity> forms) {
return forms.stream()
.flatMap(form -> {
String content = form.getForm().getContent();
return getIdAndLabelFromResult(filterByName(content, "fileupload")).stream();
})
.collect(Collectors.toMap(AmendmentFormFieldResponse::getFieldId, AmendmentFormFieldResponse::getLabel));
}
private Map<String, ApplicationFormFieldEntity> getApplicationFormFieldEntityMap(
ApplicationAmendmentRequestEntity entity, List<AmendmentFormField> amendmentFormFields) {
List<String> fieldIds = amendmentFormFields.stream()
.map(AmendmentFormField::getFieldId)
.toList();
return getApplicationFormFieldList(entity, fieldIds).stream()
.collect(Collectors.toMap(ApplicationFormFieldEntity::getFieldId, Function.identity()));
}
private void processFormFields(List<AmendmentFormField> amendmentFormFields, Map<String, String> fieldIdToLabelMap,
Map<String, ApplicationFormFieldEntity> formFieldEntityMap, ApplicationAmendmentRequestResponse response) {
List<AmendmentFormFieldResponse> formFields = new ArrayList<>();
List<ApplicationFormFieldResponseBean> fileDetails = new ArrayList<>();
for (AmendmentFormField amendmentFormField : amendmentFormFields) {
// Create form field response
createFormField(formFields, fieldIdToLabelMap, amendmentFormField);
// Create document responses
List<Long> documentIds = extractIds(amendmentFormField.getFieldValue());
List<DocumentResponseBean> documentResponseBeans = documentIds.stream()
.map(id -> {
DocumentEntity documentEntity = documentService.validateDocument(id);
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;
})
.toList();
// Map to application form field response bean
ApplicationFormFieldEntity formFieldEntity = formFieldEntityMap.get(amendmentFormField.getFieldId());
ApplicationFormFieldResponseBean responseBean = new ApplicationFormFieldResponseBean();
responseBean.setApplicationFormId(formFieldEntity.getApplicationForm().getId());
responseBean.setId(formFieldEntity.getId());
responseBean.setFieldId(amendmentFormField.getFieldId());
responseBean.setCreatedDate(formFieldEntity.getCreatedDate());
responseBean.setUpdatedDate(formFieldEntity.getUpdatedDate());
responseBean.setFieldValue(documentResponseBeans);
fileDetails.add(responseBean);
}
response.setFormFields(formFields);
response.setApplicationFormFields(fileDetails);
}
private String buildBeneficiaryName(UserEntity userEntity) {
if (userEntity.getBeneficiary() == null) {
return "";
}
String firstName = userEntity.getBeneficiary().getFirstName();
String lastName = userEntity.getBeneficiary().getLastName();
return (firstName != null ? firstName : "") +
(lastName != null && !lastName.isBlank() ? " " + lastName : "");
}
private void createFormField(List<AmendmentFormFieldResponse> formFields, Map<String, String> fieldIdToLabelMap,
AmendmentFormField amendmentFormField) {
AmendmentFormFieldResponse formField = new AmendmentFormFieldResponse();
String label = fieldIdToLabelMap.get(amendmentFormField.getFieldId());
formField.setFieldId(amendmentFormField.getFieldId());
formField.setLabel(label);
formField.setSelected(true);
formFields.add(formField);
}
public ApplicationAmendmentRequestEntity validateApplicationAmendmentRequest(Long id) {
return applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG)));
@@ -447,11 +454,19 @@ public class ApplicationAmendmentRequestDao {
ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
setIfUpdated(existingApplicationAmendment::getNote, existingApplicationAmendment::setNote, updateRequest.getNote());
if (updateRequest.getApplicationFormFields() != null) {
updateApplicationFormFields(existingApplicationAmendment, updateRequest.getApplicationFormFields());
updateFormFieldsJson(existingApplicationAmendment, updateRequest.getApplicationFormFields());
}
existingApplicationAmendment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
Map<String, AmendmentFormField> amendmentFormFieldMap = Utils
.convertJsonStringToList(existingApplicationAmendment.getFormFields(), AmendmentFormField.class)
.stream().collect(Collectors.toMap(AmendmentFormField::getFieldId, Function.identity()));
Map<String, ApplicationFormFieldEntity> applicationFormFieldMap = getApplicationFormFieldList(existingApplicationAmendment, amendmentFormFieldMap.keySet().stream().toList()).stream().collect(Collectors.toMap(ApplicationFormFieldEntity::getFieldId, Function.identity()));
updateRequest.getApplicationFormFields().stream().forEach(applicationFormFieldRequest->{
AmendmentFormField amendmentFormField = getAmendmentFormField(amendmentFormFieldMap,applicationFormFieldRequest.getFieldId());
ApplicationFormFieldEntity applicationFormFieldEntity = getApplicationFormField(applicationFormFieldMap, applicationFormFieldRequest.getFieldId());
updateApplicationFormField(applicationFormFieldEntity,applicationFormFieldRequest, amendmentFormField);
updateFormField(applicationFormFieldRequest, amendmentFormField);
});
existingApplicationAmendment.setFormFields(Utils.convertListToJsonString(amendmentFormFieldMap.values().stream().toList()));
ApplicationAmendmentRequestEntity updatedApplicationAmendment = saveApplicationAmendmentRequestEntity(existingApplicationAmendment);
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment);
@@ -459,184 +474,298 @@ public class ApplicationAmendmentRequestDao {
return response;
}
private void updateApplicationFormFields(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) {
if (updatedFormField.getFieldValue() == null || "".equals(updatedFormField.getFieldValue().toString().trim())) {
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationAmendment.getApplicationId());
private List<Long> updateApplicationFormField(ApplicationFormFieldEntity applicationFormFieldEntity,
ApplicationFormFieldRequestBean applicationFormFieldRequest, AmendmentFormField amendmentFormField) {
// Step 1: Extract IDs
List<Long> applicationFormFieldIds = extractIds(applicationFormFieldEntity.getFieldValue());
List<Long> amendmentFormFieldIds = extractIds(amendmentFormField.getFieldValue());
List<Long> requestedIds = extractIds(applicationFormFieldRequest.getFieldValue());
boolean fieldUpdated = false;
// Step 2: Optimize operations by finding differences
// Remove only those IDs from currentIds that exist in presentIds but not in requestedIds
List<Long> idsToRemove = amendmentFormFieldIds.stream()
.filter(id -> !requestedIds.contains(id))
.toList();
applicationFormFieldIds.removeAll(idsToRemove);
for (ApplicationFormEntity applicationForm : applicationForms) {
Optional<ApplicationFormFieldEntity> formFieldEntityOptional = applicationFormFieldRepository
.findByApplicationFormIdAndFieldId(applicationForm.getId(), updatedFormField.getFieldId());
// Add only those IDs to currentIds that exist in requestedIds but not in presentIds
List<Long> idsToAdd = requestedIds.stream()
.filter(id -> !amendmentFormFieldIds.contains(id))
.toList();
applicationFormFieldIds.addAll(idsToAdd);
if (formFieldEntityOptional.isPresent()) {
ApplicationFormFieldEntity formEntity = formFieldEntityOptional.get();
formEntity.setFieldValue(null); // Set field value to null
applicationFormFieldRepository.save(formEntity);
log.info("Set field value to null for application ID {} and field ID {}", applicationAmendment.getApplicationId(), updatedFormField.getFieldId());
fieldUpdated = true;
break;
}
}
// Step 3: Update the applicationFormFieldEntity fieldValue with requestedIds if it has changed
if (!amendmentFormFieldIds.equals(requestedIds)) {
String updatedFieldValue = applicationFormFieldIds.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
applicationFormFieldEntity.setFieldValue(updatedFieldValue);
applicationFormFieldRepository.save(applicationFormFieldEntity);
}
if (!fieldUpdated) {
throw new CustomValidationException(Status.NOT_FOUND, "No ApplicationFormField found for application ID " + applicationAmendment.getApplicationId() + " and field ID " + updatedFormField.getFieldId());
}
return;
}
// Step 4: Return the updated currentIds
return applicationFormFieldIds;
List<String> documentIds;
if (updatedFormField.getFieldValue() instanceof String && updatedFormField.getFieldValue() != null) {
documentIds = Arrays.asList(((String) updatedFormField.getFieldValue()).split(","));
} else {
log.warn("Expected fieldValue as a comma-separated String but got: {}", updatedFormField.getFieldValue());
return;
}
List<String> validDocumentIds = new ArrayList<>();
for (String documentId : documentIds) {
try {
DocumentEntity documentEntity = documentService.validateDocument(Long.parseLong(documentId.trim()));
if (documentEntity != null) {
validDocumentIds.add(documentId.trim());
} else {
log.warn("Document with ID {} does not exist. Skipping this ID.", documentId);
}
} catch (NumberFormatException e) {
log.error("Invalid document ID format: {}. Error: {}", documentId, e.getMessage());
}
}
if (!validDocumentIds.isEmpty()) {
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationAmendment.getApplicationId());
boolean fieldUpdated = false;
// Parse the formFields JSON string to get amendment field values
String amendmentFieldValue = null;
try {
ObjectMapper mapper = new ObjectMapper();
List<ApplicationFormFieldRequestBean> amendmentFields = mapper.readValue(
applicationAmendment.getFormFields(),
mapper.getTypeFactory().constructCollectionType(List.class, ApplicationFormFieldRequestBean.class)
);
// Find the matching field value and convert to string if found
Optional<Object> amendmentFieldObj = amendmentFields.stream()
.filter(field -> updatedFormField.getFieldId().equals(field.getFieldId()))
.map(ApplicationFormFieldRequestBean::getFieldValue)
.findFirst();
if (amendmentFieldObj.isPresent() && amendmentFieldObj.get() instanceof String) {
amendmentFieldValue = (String) amendmentFieldObj.get();
}
} catch (JsonProcessingException e) {
log.error("Error parsing formFields JSON: {}", e.getMessage());
return;
}
if (amendmentFieldValue == null) {
log.warn("No matching field found in amendment for field ID {}", updatedFormField.getFieldId());
return;
}
List<String> amendmentDocumentIds = Arrays.asList(amendmentFieldValue.split(","));
for (ApplicationFormEntity applicationForm : applicationForms) {
Optional<ApplicationFormFieldEntity> formFieldEntityOptional = applicationFormFieldRepository
.findByApplicationFormIdAndFieldId(applicationForm.getId(), updatedFormField.getFieldId());
if (formFieldEntityOptional.isPresent()) {
ApplicationFormFieldEntity formEntity = formFieldEntityOptional.get();
// Retrieve existing document IDs in ApplicationFormFieldTable
String existingFieldValue = formEntity.getFieldValue();
Set<String> existingDocumentIds = existingFieldValue != null
? new HashSet<>(Arrays.asList(existingFieldValue.split(",")))
: new HashSet<>();
// Remove amendment documents from existing document IDs
existingDocumentIds.removeAll(amendmentDocumentIds);
// Add valid new document IDs from the request
existingDocumentIds.addAll(validDocumentIds);
applicationDao.updateDocumentDeletionStatus(formEntity, updatedFormField, formEntity.getApplicationForm().getForm(), null,validDocumentIds,true);
// Set the combined document IDs back as the field value
formEntity.setFieldValue(String.join(",", existingDocumentIds));
applicationFormFieldRepository.save(formEntity);
log.info("Updated field value for application ID {} and field ID {} with document IDs {}",
applicationAmendment.getApplicationId(), updatedFormField.getFieldId(), String.join(",", existingDocumentIds));
fieldUpdated = true;
break;
}
}
if (!fieldUpdated) {
throw new CustomValidationException(Status.NOT_FOUND,
String.format("No ApplicationFormField found for application ID %s and field ID %s. Skipping update.",
applicationAmendment.getApplicationId(), updatedFormField.getFieldId()));
}
} else {
log.warn("No valid document IDs found for update. Skipping field ID {}", updatedFormField.getFieldId());
}
}
}
private void updateFormFieldsJson(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) {
if (updatedFormField != null) {
try {
// Step 1: Fetch the existing form fields JSON
String existingFormFieldsJson = applicationAmendment.getFormFields();
List<ApplicationFormFieldRequestBean> formFieldsList;
if (existingFormFieldsJson == null || existingFormFieldsJson.isEmpty()) {
formFieldsList = new ArrayList<>(); // If no existing data, start with an empty list
} else {
// Step 2: Deserialize the existing JSON into a list of objects
formFieldsList = new ObjectMapper().readValue(existingFormFieldsJson, new TypeReference<List<ApplicationFormFieldRequestBean>>() {
});
}
// Step 3: Check if the field ID already exists in the list and update it
boolean fieldUpdated = false;
for (ApplicationFormFieldRequestBean field : formFieldsList) {
if (field.getFieldId().equals(updatedFormField.getFieldId())) {
field.setFieldValue(updatedFormField.getFieldValue()); // Update field value
fieldUpdated = true;
break;
}
}
// If field wasn't updated, log a warning message instead of adding a new field
if (!fieldUpdated) {
log.warn("Field ID {} does not exist in the form fields for application amendment ID {}", updatedFormField.getFieldId(), applicationAmendment.getId());
throw new CustomValidationException(Status.NOT_FOUND, "Field ID {} does not exist in the form fields for application amendment ID {}");
}
// Step 4: Serialize the updated list back to JSON if the update was successful
String updatedFormFieldsJson = new ObjectMapper().writeValueAsString(formFieldsList);
applicationAmendment.setFormFields(updatedFormFieldsJson); // Update the form fields with the modified list
log.info("Updated form fields JSON for application amendment ID {}: {}", applicationAmendment.getId(), updatedFormFieldsJson);
} catch (JsonProcessingException e) {
log.error("Error processing JSON for form fields for application amendment ID {}: {}", applicationAmendment.getId(), e.getMessage());
throw new CustomValidationException(Status.BAD_REQUEST, "Error processing JSON for form fields");
}
} else {
log.warn("No form field data to update for application amendment ID {}", applicationAmendment.getId());
throw new CustomValidationException(Status.NOT_FOUND, "No form field data to update for application amendment ID {}");
}
}
private ApplicationFormFieldEntity getApplicationFormField(
Map<String, ApplicationFormFieldEntity> applicationFormFieldMap, String fieldId) {
ApplicationFormFieldEntity applicationFormFieldEntity = applicationFormFieldMap.get(fieldId);
if (applicationFormFieldEntity == null) {
throw new CustomValidationException(Status.BAD_REQUEST, GepafinConstant.APPLICATION_FORM_FIELD_NOT_FOUND);
}
return applicationFormFieldEntity;
}
public List<ApplicationAmendmentRequestResponse> getAllAmendmentRequestByBeneficiaryId(Long beneficiaryId) {
UserEntity userEntity = userService.validateUser(beneficiaryId);
private List<ApplicationFormFieldEntity> getApplicationFormFieldList(
ApplicationAmendmentRequestEntity applicationAmendment,
List<String> fieldIds) {
List<ApplicationFormEntity> applicationFormList = applicationFormRepository
.findByApplicationId(applicationAmendment.getApplicationId());
return applicationFormList.stream().flatMap(applicationForm -> applicationFormFieldRepository
.findByApplicationFormIdAndFieldIdIn(applicationForm.getId(), fieldIds).stream()).toList();
}
private AmendmentFormField getAmendmentFormField(Map<String, AmendmentFormField> amendmentFormFieldMap,
String fieldId) {
AmendmentFormField amendmentFormField = amendmentFormFieldMap.get(fieldId);
if (amendmentFormField == null) {
throw new CustomValidationException(Status.BAD_REQUEST, GepafinConstant.APPLICATION_FORM_FIELD_NOT_FOUND);
}
return amendmentFormField;
}
private void updateFormField(ApplicationFormFieldRequestBean applicationFormFieldRequest,
AmendmentFormField amendmentFormField) {
List<Long> requestedDocumentIds = extractIds(applicationFormFieldRequest.getFieldValue());
List<Long> existingDocumentIds = extractIds(amendmentFormField.getFieldValue());
if (requestedDocumentIds.isEmpty()) {
if (!existingDocumentIds.isEmpty()) {
existingDocumentIds.forEach(this::softDeleteDocument);
amendmentFormField.setFieldValue(null);
setIsUploadedBy(amendmentFormField);
}
return;
}
requestedDocumentIds.forEach(documentId -> documentService.validateDocument(documentId).getId());
existingDocumentIds.stream().filter(documentId -> !requestedDocumentIds.contains(documentId))
.forEach(this::softDeleteDocument);
String newFieldValue = String.join(",",
requestedDocumentIds.stream().map(String::valueOf).collect(Collectors.toList()));
if (!newFieldValue.equals(amendmentFormField.getFieldValue())) {
amendmentFormField.setFieldValue(newFieldValue);
setIsUploadedBy(amendmentFormField);
}
}
private List<Long> extractIds(Object fieldValue) {
if (fieldValue instanceof String && !StringUtils.isEmpty((String) fieldValue)) {
return Arrays.stream(((String) fieldValue).split(","))
.map(Long::valueOf)
.collect(Collectors.toList());
}
return Collections.emptyList();
}
private void setIsUploadedBy(AmendmentFormField amendmentFormField) {
if(validator.checkIsBeneficiary()) {
amendmentFormField.setIsUploadedBy(AmendmentIsUploadedByEnum.BENEFICIARY.getValue());
}else {
amendmentFormField.setIsUploadedBy(AmendmentIsUploadedByEnum.PRE_INSTRUCTOR.getValue());
}
}
// private void updateApplicationFormFields(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) {
// if (updatedFormField.getFieldValue() == null || "".equals(updatedFormField.getFieldValue().toString().trim())) {
// List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationAmendment.getApplicationId());
//
// boolean fieldUpdated = false;
//
// for (ApplicationFormEntity applicationForm : applicationForms) {
// Optional<ApplicationFormFieldEntity> formFieldEntityOptional = applicationFormFieldRepository
// .findByApplicationFormIdAndFieldId(applicationForm.getId(), updatedFormField.getFieldId());
//
// if (formFieldEntityOptional.isPresent()) {
// ApplicationFormFieldEntity formEntity = formFieldEntityOptional.get();
// formEntity.setFieldValue(null); // Set field value to null
// applicationFormFieldRepository.save(formEntity);
// log.info("Set field value to null for application ID {} and field ID {}", applicationAmendment.getApplicationId(), updatedFormField.getFieldId());
// fieldUpdated = true;
// break;
// }
// }
//
// if (!fieldUpdated) {
// throw new CustomValidationException(Status.NOT_FOUND, "No ApplicationFormField found for application ID " + applicationAmendment.getApplicationId() + " and field ID " + updatedFormField.getFieldId());
// }
// return;
// }
//
// List<String> documentIds;
//
// if (updatedFormField.getFieldValue() instanceof String && updatedFormField.getFieldValue() != null) {
// documentIds = Arrays.asList(((String) updatedFormField.getFieldValue()).split(","));
// } else {
// log.warn("Expected fieldValue as a comma-separated String but got: {}", updatedFormField.getFieldValue());
// return;
// }
//
// List<String> validDocumentIds = new ArrayList<>();
// for (String documentId : documentIds) {
// try {
// DocumentEntity documentEntity = documentService.validateDocument(Long.parseLong(documentId.trim()));
// if (documentEntity != null) {
// validDocumentIds.add(documentId.trim());
// } else {
// log.warn("Document with ID {} does not exist. Skipping this ID.", documentId);
// }
// } catch (NumberFormatException e) {
// log.error("Invalid document ID format: {}. Error: {}", documentId, e.getMessage());
// }
// }
//
// if (!validDocumentIds.isEmpty()) {
// List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationAmendment.getApplicationId());
//
// boolean fieldUpdated = false;
//
// // Parse the formFields JSON string to get amendment field values
// String amendmentFieldValue = null;
// try {
// ObjectMapper mapper = new ObjectMapper();
// List<ApplicationFormFieldRequestBean> amendmentFields = mapper.readValue(
// applicationAmendment.getFormFields(),
// mapper.getTypeFactory().constructCollectionType(List.class, ApplicationFormFieldRequestBean.class)
// );
//
// // Find the matching field value and convert to string if found
// Optional<Object> amendmentFieldObj = amendmentFields.stream()
// .filter(field -> updatedFormField.getFieldId().equals(field.getFieldId()))
// .map(ApplicationFormFieldRequestBean::getFieldValue)
// .findFirst();
//
// if (amendmentFieldObj.isPresent() && amendmentFieldObj.get() instanceof String) {
// amendmentFieldValue = (String) amendmentFieldObj.get();
// }
//
// } catch (JsonProcessingException e) {
// log.error("Error parsing formFields JSON: {}", e.getMessage());
// return;
// }
//
// if (amendmentFieldValue == null) {
// log.warn("No matching field found in amendment for field ID {}", updatedFormField.getFieldId());
// return;
// }
//
// List<String> amendmentDocumentIds = Arrays.asList(amendmentFieldValue.split(","));
//
// for (ApplicationFormEntity applicationForm : applicationForms) {
// Optional<ApplicationFormFieldEntity> formFieldEntityOptional = applicationFormFieldRepository
// .findByApplicationFormIdAndFieldId(applicationForm.getId(), updatedFormField.getFieldId());
//
// if (formFieldEntityOptional.isPresent()) {
// ApplicationFormFieldEntity formEntity = formFieldEntityOptional.get();
//
// // Retrieve existing document IDs in ApplicationFormFieldTable
// String existingFieldValue = formEntity.getFieldValue();
// Set<String> existingDocumentIds = existingFieldValue != null
// ? new HashSet<>(Arrays.asList(existingFieldValue.split(",")))
// : new HashSet<>();
//
// // Remove amendment documents from existing document IDs
// existingDocumentIds.removeAll(amendmentDocumentIds);
//
// // Add valid new document IDs from the request
// existingDocumentIds.addAll(validDocumentIds);
// applicationDao.updateDocumentDeletionStatus(formEntity, updatedFormField, formEntity.getApplicationForm().getForm(), null,validDocumentIds,true);
// // Set the combined document IDs back as the field value
// formEntity.setFieldValue(String.join(",", existingDocumentIds));
// applicationFormFieldRepository.save(formEntity);
// log.info("Updated field value for application ID {} and field ID {} with document IDs {}",
// applicationAmendment.getApplicationId(), updatedFormField.getFieldId(), String.join(",", existingDocumentIds));
// fieldUpdated = true;
// break;
// }
// }
//
// if (!fieldUpdated) {
// throw new CustomValidationException(Status.NOT_FOUND,
// String.format("No ApplicationFormField found for application ID %s and field ID %s. Skipping update.",
// applicationAmendment.getApplicationId(), updatedFormField.getFieldId()));
// }
// } else {
// log.warn("No valid document IDs found for update. Skipping field ID {}", updatedFormField.getFieldId());
// }
// }
//
//
// private void updateFormFieldsJson(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) {
// if (updatedFormField != null) {
// try {
// // Step 1: Fetch the existing form fields JSON
// String existingFormFieldsJson = applicationAmendment.getFormFields();
// List<ApplicationFormFieldRequestBean> formFieldsList;
//
// if (existingFormFieldsJson == null || existingFormFieldsJson.isEmpty()) {
// formFieldsList = new ArrayList<>(); // If no existing data, start with an empty list
// } else {
// // Step 2: Deserialize the existing JSON into a list of objects
// formFieldsList = new ObjectMapper().readValue(existingFormFieldsJson, new TypeReference<List<ApplicationFormFieldRequestBean>>() {
// });
// }
//
// // Step 3: Check if the field ID already exists in the list and update it
// boolean fieldUpdated = false;
// for (ApplicationFormFieldRequestBean field : formFieldsList) {
// if (field.getFieldId().equals(updatedFormField.getFieldId())) {
// field.setFieldValue(updatedFormField.getFieldValue()); // Update field value
// fieldUpdated = true;
// break;
// }
// }
//
// // If field wasn't updated, log a warning message instead of adding a new field
// if (!fieldUpdated) {
// log.warn("Field ID {} does not exist in the form fields for application amendment ID {}", updatedFormField.getFieldId(), applicationAmendment.getId());
// throw new CustomValidationException(Status.NOT_FOUND, "Field ID {} does not exist in the form fields for application amendment ID {}");
//
// }
//
// // Step 4: Serialize the updated list back to JSON if the update was successful
// String updatedFormFieldsJson = new ObjectMapper().writeValueAsString(formFieldsList);
// applicationAmendment.setFormFields(updatedFormFieldsJson); // Update the form fields with the modified list
//
// log.info("Updated form fields JSON for application amendment ID {}: {}", applicationAmendment.getId(), updatedFormFieldsJson);
//
// } catch (JsonProcessingException e) {
// log.error("Error processing JSON for form fields for application amendment ID {}: {}", applicationAmendment.getId(), e.getMessage());
// throw new CustomValidationException(Status.BAD_REQUEST, "Error processing JSON for form fields");
// }
// } else {
// log.warn("No form field data to update for application amendment ID {}", applicationAmendment.getId());
// throw new CustomValidationException(Status.NOT_FOUND, "No form field data to update for application amendment ID {}");
// }
// }
public List<ApplicationAmendmentRequestResponse> getAllAmendmentRequestByBeneficiaryId(Long beneficiaryUserId) {
UserEntity userEntity = userService.validateUser(beneficiaryUserId);
List<ApplicationAmendmentRequestEntity> entities =
applicationAmendmentRequestRepository.findByUserId(beneficiaryId);
applicationAmendmentRequestRepository.findByUserId(beneficiaryUserId);
return entities.stream()
.map(this::convertEntityToResponse)
@@ -779,4 +908,9 @@ public class ApplicationAmendmentRequestDao {
}
private void softDeleteDocument(Long documentId) {
documentService.deleteFile(documentId);
}
}

View File

@@ -118,7 +118,7 @@ public class DocumentDao {
public DocumentEntity validateDocument(Long id) {
return documentRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
return documentRepository.findByIdAndNotDeleted(id).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND)));
}

View File

@@ -0,0 +1,33 @@
package net.gepafin.tendermanagement.model.request;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Data;
@Data
public class AmendmentFormField {
private String fieldId;
private String fieldValue;
private String isUploadedBy;
public enum AmendmentIsUploadedByEnum {
PRE_INSTRUCTOR("PRE_INSTRUCTOR"),
BENEFICIARY("BENEFICIARY");
private String value;
AmendmentIsUploadedByEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
}

View File

@@ -1,9 +1,11 @@
package net.gepafin.tendermanagement.model.request;
import java.util.List;
import lombok.Data;
@Data
public class ApplicationAmendmentRequestBean {
private String note;
private ApplicationFormFieldRequestBean applicationFormFields;
private List<ApplicationFormFieldRequestBean> applicationFormFields;
}

View File

@@ -38,4 +38,6 @@ public interface ApplicationFormFieldRepository extends JpaRepository<Applicatio
public ApplicationFormFieldEntity findByFieldId(String FieldId);
Optional<ApplicationFormFieldEntity> findByApplicationFormIdAndFieldId(Long id, String fieldId);
public List<ApplicationFormFieldEntity> findByApplicationFormIdAndFieldIdIn(Long id, List<String> fieldIds);
}

View File

@@ -87,13 +87,12 @@ public class ApplicationAmendmentRequestServiceImpl implements ApplicationAmendm
@Override
public ApplicationAmendmentRequestResponse updateApplicationAmendment(HttpServletRequest request, Long id, ApplicationAmendmentRequestBean applicationAmendmentRequestBean) {
ApplicationAmendmentRequestEntity amendment = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG)));
ApplicationAmendmentRequestEntity amendment = applicationAmendmentRequestDao.validateApplicationAmendmentRequest(id);
Optional<ApplicationEvaluationEntity> entityOptional = applicationEvaluationRepository.findByIdAndIsDeletedFalse(amendment.getApplicationEvaluationEntity().getId());
if (entityOptional.isPresent()) {
UserEntity user = validator.validatePreInstructor(request, entityOptional.get().getUserId());
if (Boolean.FALSE.equals(validator.checkIsBeneficiary())) {
validator.validatePreInstructor(request, amendment.getApplicationEvaluationEntity().getUserId());
} else {
validator.validateUserId(request, amendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getUserId());
}
return applicationAmendmentRequestDao.updateApplicationAmendment(id,applicationAmendmentRequestBean);
}
@@ -105,9 +104,9 @@ public class ApplicationAmendmentRequestServiceImpl implements ApplicationAmendm
}
@Override
public List<ApplicationAmendmentRequestResponse> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryId) {
public List<ApplicationAmendmentRequestResponse> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryUserId) {
UserEntity user= validator.validateUser(request);
return applicationAmendmentRequestDao.getAllAmendmentRequestByBeneficiaryId(beneficiaryId);
return applicationAmendmentRequestDao.getAllAmendmentRequestByBeneficiaryId(beneficiaryUserId);
}
@Override

View File

@@ -115,7 +115,7 @@ public interface ApplicationAmendmentRequestApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/beneficiary/user/{id}", produces = "application/json")
ResponseEntity<Response<List<ApplicationAmendmentRequestResponse>>> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request,
@Parameter(description = "Id", required = false) @PathVariable(value = "id",required = false) Long beneficiaryId);
@Parameter(description = "Id", required = false) @PathVariable(value = "id",required = false) Long beneficiaryUserId);
@Operation(summary = "Api to extend response days for an amendment request",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),

View File

@@ -76,9 +76,9 @@ public class ApplicationAmendmentRequestController implements ApplicationAmendme
}
@Override
public ResponseEntity<Response<List<ApplicationAmendmentRequestResponse>>> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryId) {
public ResponseEntity<Response<List<ApplicationAmendmentRequestResponse>>> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryUserId) {
log.info("Get All Application Amendment Request By Beneficiary ID");
List<ApplicationAmendmentRequestResponse> applicationAmendmentRequestResponseList = applicationAmendmentRequestService.getAllAmendmentRequestByBeneficiaryId(request, beneficiaryId);
List<ApplicationAmendmentRequestResponse> applicationAmendmentRequestResponseList = applicationAmendmentRequestService.getAllAmendmentRequestByBeneficiaryId(request, beneficiaryUserId);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(applicationAmendmentRequestResponseList, Status.SUCCESS, Translator.toLocale(GepafinConstant.GET_APPLICATION_AMENDMENT_SUCCESS_MSG)));
}