From ac6c4ba0b0de322eb7ca3a808757f1bfb3edf139 Mon Sep 17 00:00:00 2001 From: harish Date: Sun, 24 Nov 2024 20:14:09 +0530 Subject: [PATCH 1/2] updated code for amendment api --- .../dao/ApplicationAmendmentRequestDao.java | 730 +++++++++++------- .../tendermanagement/dao/DocumentDao.java | 2 +- .../model/request/AmendmentFormField.java | 33 + .../ApplicationAmendmentRequestBean.java | 4 +- .../ApplicationFormFieldRepository.java | 2 + ...pplicationAmendmentRequestServiceImpl.java | 15 +- .../api/ApplicationAmendmentRequestApi.java | 2 +- ...ApplicationAmendmentRequestController.java | 4 +- 8 files changed, 481 insertions(+), 311 deletions(-) create mode 100644 src/main/java/net/gepafin/tendermanagement/model/request/AmendmentFormField.java diff --git a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java index 4f968499..45d6fdb3 100644 --- a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java +++ b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java @@ -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 formFieldRequestBean = applicationAmendmentRequest.getFormFields().stream() + List 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); + + List forms = applicationFormRepository.findByApplicationId(applicationAmendmentRequestEntity.getApplicationId()); + Map fieldIdToLabelMap = extractFieldIdToLabelMap(forms); - 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 amendmentFormFields = Utils.convertJsonStringToList( + applicationAmendmentRequestEntity.getFormFields(), AmendmentFormField.class); + Map formFieldEntityMap = getApplicationFormFieldEntityMap(applicationAmendmentRequestEntity, amendmentFormFields); - LocalDateTime expirationDate = startDate.plus(expirationDays, ChronoUnit.DAYS); - applicationAmendmentRequestResponse.setExpirationDate(expirationDate); + processFormFields(amendmentFormFields, fieldIdToLabelMap, formFieldEntityMap, response); - 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() : ""; - - String beneficiaryName = (!firstName.isBlank() ? firstName : "") + - (!lastName.isBlank() ? " " + lastName : ""); - - beneficiaryName = beneficiaryName.isBlank() ? "" : beneficiaryName; - applicationAmendmentRequestResponse.setCallName(callName); - applicationAmendmentRequestResponse.setProtocolNumber(protocolNumber); - applicationAmendmentRequestResponse.setBeneficiaryName(beneficiaryName); - - List forms = applicationFormRepository.findByApplicationId(applicationId); - List allFormFields = new ArrayList<>(); - - for (ApplicationFormEntity form : forms) { - String content = form.getForm().getContent(); - List> result = filterByName(content, "fileupload"); - allFormFields.addAll(getIdAndLabelFromResult(result)); - } - - Map fieldIdToLabelMap = allFormFields.stream() - .collect(Collectors.toMap(AmendmentFormFieldResponse::getFieldId, AmendmentFormFieldResponse::getLabel)); - - String formFieldsJson = applicationAmendmentRequestEntity.getFormFields(); - List formFields = Utils.convertJsonToList( - formFieldsJson, new TypeReference>() { - }); - - 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 applicationFormFields = Utils.convertJsonToList( - formFieldsJson, new TypeReference>() { - }); - - List fileDetailResponses = new ArrayList<>(); - for (ApplicationFormFieldResponseBean field : applicationFormFields) { - ApplicationFormFieldResponseBean responseBean = new ApplicationFormFieldResponseBean(); - responseBean.setFieldId(field.getFieldId()); - - Optional 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 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 extractFieldIdToLabelMap(List 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 getApplicationFormFieldEntityMap( + ApplicationAmendmentRequestEntity entity, List amendmentFormFields) { + List fieldIds = amendmentFormFields.stream() + .map(AmendmentFormField::getFieldId) + .toList(); + return getApplicationFormFieldList(entity, fieldIds).stream() + .collect(Collectors.toMap(ApplicationFormFieldEntity::getFieldId, Function.identity())); + } + + private void processFormFields(List amendmentFormFields, Map fieldIdToLabelMap, + Map formFieldEntityMap, ApplicationAmendmentRequestResponse response) { + List formFields = new ArrayList<>(); + List fileDetails = new ArrayList<>(); + + for (AmendmentFormField amendmentFormField : amendmentFormFields) { + // Create form field response + createFormField(formFields, fieldIdToLabelMap, amendmentFormField); + + // Create document responses + List documentIds = extractIds(amendmentFormField.getFieldValue()); + List 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 formFields, Map 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,196 +454,318 @@ 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 amendmentFormFieldMap = Utils + .convertJsonStringToList(existingApplicationAmendment.getFormFields(), AmendmentFormField.class) + .stream().collect(Collectors.toMap(AmendmentFormField::getFieldId, Function.identity())); + Map 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); log.info("Application Amendment updated successfully: {}", response); return response; } - private void updateApplicationFormFields(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) { - if (updatedFormField.getFieldValue() == null || "".equals(updatedFormField.getFieldValue().toString().trim())) { - List applicationForms = applicationFormRepository.findByApplicationId(applicationAmendment.getApplicationId()); + private List updateApplicationFormField(ApplicationFormFieldEntity applicationFormFieldEntity, + ApplicationFormFieldRequestBean applicationFormFieldRequest, AmendmentFormField amendmentFormField) { + // Step 1: Extract IDs + List applicationFormFieldIds = extractIds(applicationFormFieldEntity.getFieldValue()); + List amendmentFormFieldIds = extractIds(amendmentFormField.getFieldValue()); + List 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 idsToRemove = amendmentFormFieldIds.stream() + .filter(id -> !requestedIds.contains(id)) + .toList(); + applicationFormFieldIds.removeAll(idsToRemove); - for (ApplicationFormEntity applicationForm : applicationForms) { - Optional formFieldEntityOptional = applicationFormFieldRepository - .findByApplicationFormIdAndFieldId(applicationForm.getId(), updatedFormField.getFieldId()); + // Add only those IDs to currentIds that exist in requestedIds but not in presentIds + List 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; - } - - List 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 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 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 amendmentFields = mapper.readValue( - applicationAmendment.getFormFields(), - mapper.getTypeFactory().constructCollectionType(List.class, ApplicationFormFieldRequestBean.class) - ); - - // Find the matching field value and convert to string if found - Optional 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 amendmentDocumentIds = Arrays.asList(amendmentFieldValue.split(",")); - - for (ApplicationFormEntity applicationForm : applicationForms) { - Optional 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 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()); - } - } + // Step 4: Return the updated currentIds + return applicationFormFieldIds; + + } - private void updateFormFieldsJson(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) { - if (updatedFormField != null) { - try { - // Step 1: Fetch the existing form fields JSON - String existingFormFieldsJson = applicationAmendment.getFormFields(); - List 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>() { - }); - } - - // 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 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 getAllAmendmentRequestByBeneficiaryId(Long beneficiaryId) { - UserEntity userEntity = userService.validateUser(beneficiaryId); + private List getApplicationFormFieldList( + ApplicationAmendmentRequestEntity applicationAmendment, + List fieldIds) { + List applicationFormList = applicationFormRepository + .findByApplicationId(applicationAmendment.getApplicationId()); + + return applicationFormList.stream().flatMap(applicationForm -> applicationFormFieldRepository + .findByApplicationFormIdAndFieldIdIn(applicationForm.getId(), fieldIds).stream()).toList(); + } + + + private AmendmentFormField getAmendmentFormField(Map 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 requestedDocumentIds = extractIds(applicationFormFieldRequest.getFieldValue()); + List 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 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 applicationForms = applicationFormRepository.findByApplicationId(applicationAmendment.getApplicationId()); +// +// boolean fieldUpdated = false; +// +// for (ApplicationFormEntity applicationForm : applicationForms) { +// Optional 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 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 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 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 amendmentFields = mapper.readValue( +// applicationAmendment.getFormFields(), +// mapper.getTypeFactory().constructCollectionType(List.class, ApplicationFormFieldRequestBean.class) +// ); +// +// // Find the matching field value and convert to string if found +// Optional 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 amendmentDocumentIds = Arrays.asList(amendmentFieldValue.split(",")); +// +// for (ApplicationFormEntity applicationForm : applicationForms) { +// Optional 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 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 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>() { +// }); +// } +// +// // 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 getAllAmendmentRequestByBeneficiaryId(Long beneficiaryUserId) { + UserEntity userEntity = userService.validateUser(beneficiaryUserId); List 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); + } + + } diff --git a/src/main/java/net/gepafin/tendermanagement/dao/DocumentDao.java b/src/main/java/net/gepafin/tendermanagement/dao/DocumentDao.java index 6f8e3243..71655909 100644 --- a/src/main/java/net/gepafin/tendermanagement/dao/DocumentDao.java +++ b/src/main/java/net/gepafin/tendermanagement/dao/DocumentDao.java @@ -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))); } diff --git a/src/main/java/net/gepafin/tendermanagement/model/request/AmendmentFormField.java b/src/main/java/net/gepafin/tendermanagement/model/request/AmendmentFormField.java new file mode 100644 index 00000000..95f158c3 --- /dev/null +++ b/src/main/java/net/gepafin/tendermanagement/model/request/AmendmentFormField.java @@ -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; + } + } + +} diff --git a/src/main/java/net/gepafin/tendermanagement/model/request/ApplicationAmendmentRequestBean.java b/src/main/java/net/gepafin/tendermanagement/model/request/ApplicationAmendmentRequestBean.java index c3c5aeb5..94141ef0 100644 --- a/src/main/java/net/gepafin/tendermanagement/model/request/ApplicationAmendmentRequestBean.java +++ b/src/main/java/net/gepafin/tendermanagement/model/request/ApplicationAmendmentRequestBean.java @@ -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 applicationFormFields; } diff --git a/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationFormFieldRepository.java b/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationFormFieldRepository.java index b989e2dd..7a2652ad 100644 --- a/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationFormFieldRepository.java +++ b/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationFormFieldRepository.java @@ -38,4 +38,6 @@ public interface ApplicationFormFieldRepository extends JpaRepository findByApplicationFormIdAndFieldId(Long id, String fieldId); + + public List findByApplicationFormIdAndFieldIdIn(Long id, List fieldIds); } diff --git a/src/main/java/net/gepafin/tendermanagement/service/impl/ApplicationAmendmentRequestServiceImpl.java b/src/main/java/net/gepafin/tendermanagement/service/impl/ApplicationAmendmentRequestServiceImpl.java index 1f6f2f84..4d3092a3 100644 --- a/src/main/java/net/gepafin/tendermanagement/service/impl/ApplicationAmendmentRequestServiceImpl.java +++ b/src/main/java/net/gepafin/tendermanagement/service/impl/ApplicationAmendmentRequestServiceImpl.java @@ -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 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 getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryId) { + public List getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryUserId) { UserEntity user= validator.validateUser(request); - return applicationAmendmentRequestDao.getAllAmendmentRequestByBeneficiaryId(beneficiaryId); + return applicationAmendmentRequestDao.getAllAmendmentRequestByBeneficiaryId(beneficiaryUserId); } @Override diff --git a/src/main/java/net/gepafin/tendermanagement/web/rest/api/ApplicationAmendmentRequestApi.java b/src/main/java/net/gepafin/tendermanagement/web/rest/api/ApplicationAmendmentRequestApi.java index 651680ff..0918b918 100644 --- a/src/main/java/net/gepafin/tendermanagement/web/rest/api/ApplicationAmendmentRequestApi.java +++ b/src/main/java/net/gepafin/tendermanagement/web/rest/api/ApplicationAmendmentRequestApi.java @@ -115,7 +115,7 @@ public interface ApplicationAmendmentRequestApi { @ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) }) @GetMapping(value = "/beneficiary/user/{id}", produces = "application/json") ResponseEntity>> 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"), diff --git a/src/main/java/net/gepafin/tendermanagement/web/rest/api/impl/ApplicationAmendmentRequestController.java b/src/main/java/net/gepafin/tendermanagement/web/rest/api/impl/ApplicationAmendmentRequestController.java index bd66efd1..5bf3234e 100644 --- a/src/main/java/net/gepafin/tendermanagement/web/rest/api/impl/ApplicationAmendmentRequestController.java +++ b/src/main/java/net/gepafin/tendermanagement/web/rest/api/impl/ApplicationAmendmentRequestController.java @@ -76,9 +76,9 @@ public class ApplicationAmendmentRequestController implements ApplicationAmendme } @Override - public ResponseEntity>> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryId) { + public ResponseEntity>> getAllAmendmentRequestByBeneficiaryId(HttpServletRequest request, Long beneficiaryUserId) { log.info("Get All Application Amendment Request By Beneficiary ID"); - List applicationAmendmentRequestResponseList = applicationAmendmentRequestService.getAllAmendmentRequestByBeneficiaryId(request, beneficiaryId); + List applicationAmendmentRequestResponseList = applicationAmendmentRequestService.getAllAmendmentRequestByBeneficiaryId(request, beneficiaryUserId); return ResponseEntity.status(HttpStatus.CREATED) .body(new Response<>(applicationAmendmentRequestResponseList, Status.SUCCESS, Translator.toLocale(GepafinConstant.GET_APPLICATION_AMENDMENT_SUCCESS_MSG))); } From bb34972c044b5187a098d25f8ce858a7ac15a01d Mon Sep 17 00:00:00 2001 From: rajesh Date: Sun, 24 Nov 2024 22:03:15 +0530 Subject: [PATCH 2/2] removed code smells --- .../dao/ApplicationAmendmentRequestDao.java | 28 ++++++------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java index 45d6fdb3..8f7fe151 100644 --- a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java +++ b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java @@ -1,6 +1,5 @@ package net.gepafin.tendermanagement.dao; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.persistence.criteria.Join; @@ -33,7 +32,6 @@ 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; @@ -85,21 +83,11 @@ public class ApplicationAmendmentRequestDao { @Autowired private SystemEmailTemplatesService systemEmailTemplatesService; - @Autowired - private CallDao callDao; - - @Autowired - private DocumentRepository documentRepository; - @Autowired private HubService hubService; -// @Autowired -// private MailUtil mailUtil; @Autowired private Validator validator; - @Autowired - private ApplicationDao applicationDao; @Autowired private EmailLogDao emailLogDao; @@ -460,13 +448,15 @@ public class ApplicationAmendmentRequestDao { .stream().collect(Collectors.toMap(AmendmentFormField::getFieldId, Function.identity())); Map 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())); + if(updateRequest.getApplicationFormFields() != null) { + 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);