package net.gepafin.tendermanagement.dao; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum; import net.gepafin.tendermanagement.model.response.*; import net.gepafin.tendermanagement.service.*; import net.gepafin.tendermanagement.util.DateTimeUtil; import net.gepafin.tendermanagement.util.Utils; import org.h2.util.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import net.gepafin.tendermanagement.config.Translator; import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.entities.CallEntity; import net.gepafin.tendermanagement.entities.CallTargetAudienceChecklistEntity; import net.gepafin.tendermanagement.entities.DocumentEntity; import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity; import net.gepafin.tendermanagement.entities.FaqEntity; import net.gepafin.tendermanagement.entities.LookUpDataEntity; import net.gepafin.tendermanagement.entities.LookUpDataEntity.LookUpDataTypeEnum; import net.gepafin.tendermanagement.entities.RegionEntity; import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.enums.CallStatusEnum; import net.gepafin.tendermanagement.enums.DocumentTypeEnum; import net.gepafin.tendermanagement.model.request.CreateCallRequestStep1; import net.gepafin.tendermanagement.model.request.CreateCallRequestStep2; import net.gepafin.tendermanagement.model.request.DocumentReq; import net.gepafin.tendermanagement.model.request.EvaluationCriteriaReq; import net.gepafin.tendermanagement.model.request.FaqReq; import net.gepafin.tendermanagement.model.request.LookUpDataReq; import net.gepafin.tendermanagement.model.request.UpdateCallRequestStep1; import net.gepafin.tendermanagement.repositories.CallRepository; import net.gepafin.tendermanagement.repositories.CallTargetAudienceChecklistRepository; import net.gepafin.tendermanagement.repositories.DocumentRepository; import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository; import net.gepafin.tendermanagement.repositories.FaqRepository; import net.gepafin.tendermanagement.repositories.RegionRepository; import net.gepafin.tendermanagement.service.impl.CallValidatorServiceImpl; 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 static net.gepafin.tendermanagement.enums.RoleStatusEnum.ROLE_SUPER_ADMIN; import static net.gepafin.tendermanagement.util.Utils.setIfUpdated; @Component public class CallDao { @Autowired private CallRepository callRepository; @Autowired private DocumentRepository documentRepository; @Autowired private EvaluationCriteriaRepository evaluationCriteriaRepository; @Autowired private FaqRepository faqRepository; @Autowired private RegionRepository regionRepository; @Autowired private LookUpDataService lookUpDataService; @Autowired private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository; @Autowired private UserService userService; @Autowired private FaqService faqService; @Autowired private FlowDao flowDao; @Autowired private FormDao formDao; @Value("${aws.s3.url.folder}") private String s3Folder; @Autowired private AmazonS3Service amazonS3Service; public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) { UserEntity userEntity = userService.validateUser(userId); createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId()); CallEntity callEntity = convertToCallEntity(createCallRequest); updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ); convertLookUpDataEntities(createCallRequest.getAimedTo(), callEntity, LookUpDataTypeEnum.AIMED_TO); CallResponse createCallResponseBean = getCallResponseBean(callEntity); createCallResponseBean.setCurrentStep(GepafinConstant.STEP_1); return createCallResponseBean; } public byte[] downloadCallDocumentsAsZip(Long callId) { List documents = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callId, DocumentSourceTypeEnum.CALL.getValue(),DocumentTypeEnum.DOCUMENT.getValue()); if (documents.isEmpty()) { throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND)); } try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) { for (DocumentEntity document : documents) { try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFileName())) { ZipEntry zipEntry = new ZipEntry(document.getFileName()); zos.putNextEntry(zipEntry); IOUtils.copy(fileInputStream, zos); zos.closeEntry(); } catch (IOException e) { throw new RuntimeException("Error downloading or adding document to ZIP: " + document.getFileName(), e); } } zos.finish(); return zipOutputStream.toByteArray(); } catch (IOException e) { throw new RuntimeException("Error while creating ZIP file", e); } } public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest) { CallEntity callEntity = new CallEntity(); // validateCallEntity(createCallRequest); RegionEntity region = regionRepository.findById(createCallRequest.getRegionId()) .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.REGION_NOT_FOUND))); callEntity.setRegion(region); callEntity.setName(createCallRequest.getName()); callEntity.setDescriptionShort(createCallRequest.getDescriptionShort()); callEntity.setDescriptionLong(createCallRequest.getDescriptionLong()); List dates = createCallRequest.getDates(); if(dates!=null) { if(dates.size()>1) { callEntity.setStartDate(dates.get(0)); callEntity.setEndDate(dates.get(1)); } } callEntity.setStatus(CallStatusEnum.DRAFT.getValue()); callEntity.setAmountMax(createCallRequest.getAmountMax()); callEntity.setAmount(createCallRequest.getAmount()); callEntity.setConfidi(false); if (createCallRequest.getConfidi() != null) { callEntity.setConfidi(createCallRequest.getConfidi()); } callEntity.setDocumentationRequested(createCallRequest.getDocumentationRequested()); if (createCallRequest.getAmountMin() != null && createCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) { throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG)); } callEntity.setAmountMin(createCallRequest.getAmountMin()); if(createCallRequest.getEmail()!=null && Boolean.FALSE.equals(Utils.isValidEmail(createCallRequest.getEmail()))){ throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,createCallRequest.getEmail())); } callEntity.setEmail(createCallRequest.getEmail()); callEntity.setPhoneNumber(createCallRequest.getPhoneNumber()); callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime())); callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime())); callEntity = callRepository.save(callEntity); return callEntity; } public List convertToEvaluationCriteriaEntities( List criteriaReqList, CallEntity callEntity, LookUpDataTypeEnum type) { if (criteriaReqList == null) { return null; } List existingCriteria = evaluationCriteriaRepository.findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), type.getValue()); List incomingIds = criteriaReqList.stream().map(EvaluationCriteriaReq::getId) .filter(id -> id != null && id > 0).collect(Collectors.toList()); existingCriteria.stream().filter(criteria -> !incomingIds.contains(criteria.getId())).forEach(this::softDeleteEvaluationCriteria); List evaluationCriteriaEntities = criteriaReqList.stream() .map(req -> convertToEvaluationCriteriaEntity(req, callEntity, type)).collect(Collectors.toList()); evaluationCriteriaRepository.saveAll(evaluationCriteriaEntities); return evaluationCriteriaEntities; } private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) { evaluationCriteriaEntity.setIsDeleted(true); evaluationCriteriaRepository.save(evaluationCriteriaEntity); } private EvaluationCriteriaEntity convertToEvaluationCriteriaEntity(EvaluationCriteriaReq criteriaReq, CallEntity callEntity, LookUpDataTypeEnum type) { EvaluationCriteriaEntity criteriaEntity = null; LookUpDataEntity lookupDataEntity = lookUpDataService.getOrCreateLookUpDataEntity(criteriaReq, type); if (criteriaReq.getId() != null && criteriaReq.getId() > 0) { criteriaEntity = evaluationCriteriaRepository.findById(criteriaReq.getId()) .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_NOT_FOUND))); } else { criteriaEntity = new EvaluationCriteriaEntity(); criteriaEntity.setCall(callEntity); criteriaEntity.setLookupData(lookupDataEntity); criteriaEntity.setIsDeleted(false); } setIfUpdated(criteriaEntity::getScore, criteriaEntity::setScore, criteriaReq.getScore()); if (Boolean.FALSE.equals(criteriaEntity.getLookupData().getId().equals(lookupDataEntity.getId()))) { criteriaEntity.setLookupData(lookupDataEntity); } return criteriaEntity; } public List convertToDocumentEntities(List documentReqList, Long sourceId, DocumentTypeEnum documentType) { if (documentReqList == null) { return null; } List existingDocuments = documentRepository .findBySourceIdAndTypeAndIsDeletedFalse(sourceId, documentType.getValue()); List incomingIds = documentReqList.stream().map(DocumentReq::getId).filter(id -> id != null && id > 0) .collect(Collectors.toList()); existingDocuments.stream().filter(document -> !incomingIds.contains(document.getId())) .forEach(this::softDeleteDocument); List documentEntities = documentReqList.stream() .map(req -> convertToDocumentEntity(req, sourceId)).collect(Collectors.toList()); documentRepository.saveAll(documentEntities); return documentEntities; } private void softDeleteDocument(DocumentEntity documentEntity) { documentEntity.setIsDeleted(true); documentRepository.save(documentEntity); } private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) { validateDocumentEntity(documentReq.getId()); DocumentEntity documentEntity = documentRepository.findByIdAndSourceIdAndIsDeletedFalse(documentReq.getId(),sourceId) .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND))); return documentEntity; } public List updateFaq(List faqReqList, CallEntity callEntity, UserEntity userEntity, LookUpDataTypeEnum type) { if (faqReqList == null) { return null; } List existingFaqEntities = faqRepository.findByCallIdAndIsDeletedFalse(callEntity.getId()); List incomingIds = faqReqList.stream() .map(FaqReq::getId) .filter(id -> id != null && id > 0) .collect(Collectors.toList()); existingFaqEntities.stream() .filter(entity -> !incomingIds.contains(entity.getId())) .forEach(this::softDeleteFaq); List faqEntities = faqReqList.stream() .map(req -> faqService.createOrUpdateFaqEntity(req, callEntity, userEntity, type)) .collect(Collectors.toList()); return faqEntities; } public void validateDocumentEntity(Long documentId) { if (documentId == null || documentId < 1) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.DOCUMENT_ID_NOT_FOUND)); } } public void validateEvaluationCriteriaEntity(String name) { if (!StringUtils.hasText(name)) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.NAME_NOT_EMPTY_MSG)); } } public CallResponse convertToCallResponseBean(CallEntity callEntity) { CallResponse createCallResponseBean = new CallResponse(); createCallResponseBean.setId(callEntity.getId()); createCallResponseBean.setName(callEntity.getName()); List dates = new ArrayList<>(); dates.add(callEntity.getStartDate()); dates.add(callEntity.getEndDate()); createCallResponseBean.setDates(dates); createCallResponseBean.setDescriptionShort(callEntity.getDescriptionShort()); createCallResponseBean.setDescriptionLong(callEntity.getDescriptionLong()); createCallResponseBean.setStatus(CallStatusEnum.valueOf(callEntity.getStatus())); createCallResponseBean.setRegionId(callEntity.getRegion().getId()); createCallResponseBean.setAmount(callEntity.getAmount()); createCallResponseBean.setAmountMax(callEntity.getAmountMax()); createCallResponseBean.setContactInfo(callEntity.getContactInfo()); createCallResponseBean.setSubmissionMethod(callEntity.getSubmissionMethod()); createCallResponseBean.setThreshold(callEntity.getThreshold()); createCallResponseBean.setDocumentationRequested(callEntity.getDocumentationRequested()); createCallResponseBean.setPriorityArea(callEntity.getPriorityArea()); createCallResponseBean.setConfidi(callEntity.getConfidi()); createCallResponseBean.setAmountMin(callEntity.getAmountMin()); createCallResponseBean.setPhoneNumber(callEntity.getPhoneNumber()); createCallResponseBean.setEndTime(callEntity.getEndTime()); createCallResponseBean.setStartTime(callEntity.getStartTime()); createCallResponseBean.setEmail(callEntity.getEmail()); createCallResponseBean.setCreatedDate(callEntity.getCreatedDate()); createCallResponseBean.setUpdatedDate(callEntity.getUpdatedDate()); return createCallResponseBean; } public EvaluationCriteriaResponseBean convertToEvaluationCriteriaResponseBean(EvaluationCriteriaEntity entity) { EvaluationCriteriaResponseBean responseBean = new EvaluationCriteriaResponseBean(); responseBean.setId(entity.getId()); responseBean.setLookUpDataId(entity.getLookupData().getId()); responseBean.setTitle(entity.getLookupData().getTitle()); responseBean.setValue(entity.getLookupData().getValue()); responseBean.setResponse(entity.getLookupData().getResponse()); responseBean.setScore(entity.getScore()); responseBean.setCreatedDate(entity.getCreatedDate()); responseBean.setUpdatedDate(entity.getUpdatedDate()); return responseBean; } public DocumentResponseBean convertToDocumentResponseBean(DocumentEntity entity) { DocumentResponseBean responseBean = new DocumentResponseBean(); responseBean.setId(entity.getId()); responseBean.setName(entity.getFileName()); responseBean.setType(DocumentTypeEnum.valueOf(entity.getType())); responseBean.setSource(DocumentSourceTypeEnum.valueOf(entity.getSource())); responseBean.setSourceId(entity.getSourceId()); responseBean.setFilePath(entity.getFilePath()); responseBean.setCreatedDate(entity.getCreatedDate()); responseBean.setUpdatedDate(entity.getUpdatedDate()); return responseBean; } public CallResponse assembleCreateCallResponseBean(CallEntity callEntity, List evaluationCriteriaEntities, List documentEntities, List images) { CallResponse callResponseBean = convertToCallResponseBean(callEntity); List evaluationCriteriaResponseBeans = evaluationCriteriaEntities.stream() .map(this::convertToEvaluationCriteriaResponseBean).collect(Collectors.toList()); List documentResponseBeans = documentEntities.stream() .map(this::convertToDocumentResponseBean).collect(Collectors.toList()); List imagesResponseBean = images.stream().map(this::convertToDocumentResponseBean) .collect(Collectors.toList()); CallResponse createCallResponseBean = callResponseBean; createCallResponseBean.setCriteria(evaluationCriteriaResponseBeans); createCallResponseBean.setDocs(documentResponseBeans); createCallResponseBean.setImages(imagesResponseBean); return createCallResponseBean; } public List convertLookUpDataEntities(List lookUpData, CallEntity callEntity, LookUpDataEntity.LookUpDataTypeEnum type) { if(lookUpData == null) { return null; } List lookUpDataEntities = lookUpData.stream() .map(req -> lookUpDataService.getOrCreateLookUpDataEntity(req, type)).collect(Collectors.toList()); return createCallTargetAudienceCheckList(callEntity, lookUpDataEntities); } private List createCallTargetAudienceCheckList(CallEntity callEntity, List lookUpDataEntities) { List lookUpDataResponses = new ArrayList<>(); for (LookUpDataEntity lookUpDataEntity : lookUpDataEntities) { CallTargetAudienceChecklistEntity callTargetAudienceChecklistEntity = new CallTargetAudienceChecklistEntity(); callTargetAudienceChecklistEntity.setIsValidated(false); callTargetAudienceChecklistEntity.setLookupData(lookUpDataEntity); callTargetAudienceChecklistEntity.setCall(callEntity); callTargetAudienceChecklistEntity.setIsDeleted(false); callTargetAudienceChecklistEntity = callTargetAudienceChecklistRepository .save(callTargetAudienceChecklistEntity); lookUpDataResponses.add(convertToLookUpDataResponseBean(callTargetAudienceChecklistEntity)); } return lookUpDataResponses; } public LookUpDataResponse convertToLookUpDataResponseBean( CallTargetAudienceChecklistEntity callTargetAudienceChecklistEntity) { LookUpDataResponse lookUpDataResponse = new LookUpDataResponse(); LookUpDataEntity lookUpDataEntity = callTargetAudienceChecklistEntity.getLookupData(); lookUpDataResponse.setId(callTargetAudienceChecklistEntity.getId()); lookUpDataResponse.setLookUpDataId(lookUpDataEntity.getId()); lookUpDataResponse.setValue(lookUpDataEntity.getValue()); lookUpDataResponse.setTitle(lookUpDataEntity.getTitle()); lookUpDataResponse.setResponse(lookUpDataEntity.getResponse()); lookUpDataResponse.setCreatedDate(callTargetAudienceChecklistEntity.getCreatedDate()); lookUpDataResponse.setUpdatedDate(callTargetAudienceChecklistEntity.getUpdatedDate()); return lookUpDataResponse; } public CallEntity validateCall(Long callId) { return callRepository.findById(callId).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND))); } public CallResponse getCallById(Long callId) { CallEntity callEntity = validateCall(callId); return getCallResponseBean(callEntity); } public CallResponse createCallStep2(Long callId, CreateCallRequestStep2 createCallRequest, Long userId) { CallEntity callEntity = validateCall(callId); validateUpdate(callEntity); setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold()); callRepository.save(callEntity); convertToEvaluationCriteriaEntities(createCallRequest.getCriteria(), callEntity, LookUpDataTypeEnum.EVALUATION_CRITERIA); convertToDocumentEntities(createCallRequest.getDocs(), callEntity.getId(), DocumentTypeEnum.DOCUMENT); convertToDocumentEntities(createCallRequest.getImages(), callEntity.getId(), DocumentTypeEnum.IMAGES); updateLookUpData(callEntity, createCallRequest.getCheckList(), LookUpDataTypeEnum.CHECKLIST); // List faqEntities = faqRepository.findByCallIdAndIsDeletedFalse(callEntity.getId()); // List amiedTo = callTargetAudienceChecklistRepository // .findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), LookUpDataTypeEnum.AIMED_TO.getValue()).stream() // .map(this::convertToLookUpDataResponseBean).toList(); // createCallResponseBean = assembleCreateCallResponseBean(callEntity, evaluationCriteriaEntities, // documentEntities, faqEntities, imageEntities); // createCallResponseBean.setAimedTo(amiedTo); // createCallResponseBean.setCheckList(checkList); CallResponse createCallResponseBean = getCallResponseBean(callEntity); createCallResponseBean.setCurrentStep(GepafinConstant.STEP_2); return createCallResponseBean; } public void validateUpdate(CallEntity callEntity) { if(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue())) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PUBLISHED_CALL_NOT_UPDATE)); } } public void isValidDateRange(UpdateCallRequestStep1 updateCallRequest, CallEntity callEntity) { List dates = updateCallRequest.getDates(); LocalDate startDate = (dates != null && dates.size() > 0 && dates.get(0) != null) ? dates.get(0).toLocalDate() : null; LocalDate endDate = (dates != null && dates.size() > 1 && dates.get(1) != null) ? dates.get(1).toLocalDate() : null; Boolean isValid = true; if (startDate != null && endDate != null && startDate.isAfter(endDate)) { isValid = false; } else if (startDate != null && endDate == null && callEntity.getEndDate() != null && startDate.isAfter(callEntity.getEndDate().toLocalDate())) { isValid = false; } else if (startDate == null && endDate != null && callEntity.getStartDate() != null && callEntity.getStartDate().toLocalDate().isAfter(endDate)) { isValid = false; } if (Boolean.FALSE.equals(isValid)) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_DATE_MSG)); } } public CallResponse updateCallStep1(Long callId, UpdateCallRequestStep1 updateCallRequest, Long userId) { CallEntity callEntity = validateCall(callId); if(Boolean.TRUE.equals(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue()))) { try { Utils.retainOnlySpecificFields(updateCallRequest, Collections.singletonList("faq")); } catch (IllegalAccessException e) { throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FAILED_RETAIN_FIELD)); } } UserEntity userEntity = userService.validateUser(userId); isValidDateRange(updateCallRequest, callEntity); setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName()); setIfUpdated(callEntity::getDescriptionShort, callEntity::setDescriptionShort, updateCallRequest.getDescriptionShort()); setIfUpdated(callEntity::getDescriptionLong, callEntity::setDescriptionLong, updateCallRequest.getDescriptionLong()); List dates=updateCallRequest.getDates(); if (dates != null && dates.size()>1) { if (dates.size() > 0) { setIfUpdated(callEntity::getStartDate, callEntity::setStartDate, dates.get(0)); } if (dates.size() > 1) { setIfUpdated(callEntity::getEndDate, callEntity::setEndDate, dates.get(1)); } } // setIfUpdated(callEntity::getStartDate, callEntity::setStartDate, updateCallRequest.getStartDate()); // setIfUpdated(callEntity::getEndDate, callEntity::setEndDate, updateCallRequest.getEndDate()); setIfUpdated(callEntity::getAmount, callEntity::setAmount, updateCallRequest.getAmount()); setIfUpdated(callEntity::getAmountMax, callEntity::setAmountMax, updateCallRequest.getAmountMax()); setIfUpdated(callEntity::getDocumentationRequested, callEntity::setDocumentationRequested, updateCallRequest.getDocumentationRequested()); if (updateCallRequest.getAmountMin() != null && updateCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) { throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG)); } if(updateCallRequest.getEmail()!=null && Boolean.FALSE.equals(Utils.isValidEmail(updateCallRequest.getEmail()))){ throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,updateCallRequest.getEmail())); } setIfUpdated(callEntity::getAmountMin, callEntity::setAmountMin, updateCallRequest.getAmountMin()); setIfUpdated(callEntity::getEmail, callEntity::setEmail, updateCallRequest.getEmail()); setIfUpdated(callEntity::getPhoneNumber, callEntity::setPhoneNumber, updateCallRequest.getPhoneNumber()); setIfUpdated(callEntity::getStartTime, callEntity::setStartTime, DateTimeUtil.parseTime(updateCallRequest.getStartTime())); setIfUpdated(callEntity::getEndTime, callEntity::setEndTime, DateTimeUtil.parseTime(updateCallRequest.getEndTime())); setIfUpdated(callEntity::getConfidi, callEntity::setConfidi, updateCallRequest.getConfidi()); updateLookUpData(callEntity, updateCallRequest.getAimedTo(), LookUpDataTypeEnum.AIMED_TO); updateFaq(updateCallRequest.getFaq(), callEntity, userEntity, LookUpDataTypeEnum.FAQ); CallResponse createCallResponseBean = getCallResponseBean(callEntity); createCallResponseBean.setCurrentStep(GepafinConstant.STEP_1); return createCallResponseBean; } private void softDeleteFaq(FaqEntity faqEntity) { faqEntity.setIsDeleted(true); faqRepository.save(faqEntity); } private void updateLookUpData(CallEntity callEntity, List lookupDataReqList, LookUpDataTypeEnum type) { if (lookupDataReqList == null) { return; } List existingChecklist = callTargetAudienceChecklistRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), type.getValue()); List incomingIds = lookupDataReqList.stream().map(LookUpDataReq::getId) .filter(id -> id != null && id > 0).collect(Collectors.toList()); existingChecklist.stream().filter(checklist -> !incomingIds.contains(checklist.getId())) .forEach(this::softDeleteCallTargetAudienceChecklist); lookupDataReqList .forEach(lookUpDataReq -> createOrUpdateCallTargetAudienceChecklist(lookUpDataReq, callEntity, type)); } private void createOrUpdateCallTargetAudienceChecklist(LookUpDataReq lookUpDataReq, CallEntity callEntity, LookUpDataTypeEnum type) { CallTargetAudienceChecklistEntity checklistEntity = null; LookUpDataEntity lookupDataEntity = lookUpDataService.getOrCreateLookUpDataEntity(lookUpDataReq, type); if (lookUpDataReq.getId() != null && lookUpDataReq.getId() > 0) { checklistEntity = callTargetAudienceChecklistRepository.findById(lookUpDataReq.getId()) .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND))); if (Boolean.FALSE.equals(checklistEntity.getLookupData().getId().equals(lookupDataEntity.getId()))) { checklistEntity.setLookupData(lookupDataEntity); } } else { checklistEntity = new CallTargetAudienceChecklistEntity(); checklistEntity.setCall(callEntity); checklistEntity.setLookupData(lookupDataEntity); checklistEntity.setIsValidated(false); checklistEntity.setIsDeleted(false); } callTargetAudienceChecklistRepository.save(checklistEntity); } private void softDeleteCallTargetAudienceChecklist( CallTargetAudienceChecklistEntity callTargetAudienceChecklistEntity) { callTargetAudienceChecklistEntity.setIsDeleted(true); callTargetAudienceChecklistRepository.save(callTargetAudienceChecklistEntity); } public CallDetailsResponseBean convertToCallDetailsResponseBean(CallEntity callEntity) { CallDetailsResponseBean callDetailsResponseBean = new CallDetailsResponseBean(); callDetailsResponseBean.setId(callEntity.getId()); callDetailsResponseBean.setName(callEntity.getName()); List dates = new ArrayList<>(); dates.add(callEntity.getStartDate()); dates.add(callEntity.getEndDate()); callDetailsResponseBean.setDates(dates); callDetailsResponseBean.setDescriptionShort(callEntity.getDescriptionShort()); callDetailsResponseBean.setDescriptionLong(callEntity.getDescriptionLong()); callDetailsResponseBean.setStatus(CallStatusEnum.valueOf(callEntity.getStatus())); callDetailsResponseBean.setRegionId(callEntity.getRegion().getId()); callDetailsResponseBean.setAmount(callEntity.getAmount()); callDetailsResponseBean.setAmountMax(callEntity.getAmountMax()); callDetailsResponseBean.setContactInfo(callEntity.getContactInfo()); callDetailsResponseBean.setSubmissionMethod(callEntity.getSubmissionMethod()); callDetailsResponseBean.setThreshold(callEntity.getThreshold()); callDetailsResponseBean.setDocumentationRequested(callEntity.getDocumentationRequested()); callDetailsResponseBean.setPriorityArea(callEntity.getPriorityArea()); callDetailsResponseBean.setAmountMin(callEntity.getAmountMin()); callDetailsResponseBean.setEmail(callEntity.getEmail()); callDetailsResponseBean.setEndTime(callEntity.getEndTime()); callDetailsResponseBean.setStartTime(callEntity.getStartTime()); callDetailsResponseBean.setPhoneNumber(callEntity.getPhoneNumber()); callDetailsResponseBean.setCreatedDate(callEntity.getCreatedDate()); callDetailsResponseBean.setUpdatedDate(callEntity.getUpdatedDate()); return callDetailsResponseBean; } private CallResponse getCallResponseBean(CallEntity callEntity) { List documentEntities = documentRepository.findBySourceIdAndTypeAndIsDeletedFalse(callEntity.getId(), DocumentTypeEnum.DOCUMENT.getValue()); List imageEntities = documentRepository.findBySourceIdAndTypeAndIsDeletedFalse(callEntity.getId(), DocumentTypeEnum.IMAGES.getValue()); List amiedTo = callTargetAudienceChecklistRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), LookUpDataTypeEnum.AIMED_TO.getValue()).stream() .map(this::convertToLookUpDataResponseBean).toList(); List checkList = callTargetAudienceChecklistRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), LookUpDataTypeEnum.CHECKLIST.getValue()).stream() .map(this::convertToLookUpDataResponseBean).toList(); List evaluationCriteriaEntities = evaluationCriteriaRepository .findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue()); CallResponse createCallResponseBean = assembleCreateCallResponseBean(callEntity, evaluationCriteriaEntities, documentEntities, imageEntities); createCallResponseBean.setFaq(faqService.getFaqByCallId(callEntity.getId())); createCallResponseBean.setAimedTo(amiedTo); createCallResponseBean.setCheckList(checkList); return createCallResponseBean; } public List getAllCalls(UserEntity user) { String type=user.getRoleEntity().getRoleType(); List callStatusList =CallStatusEnum.getStatusValues(); if (Boolean.FALSE.equals(ROLE_SUPER_ADMIN.getValue().equals(type))) { callStatusList = List.of(CallStatusEnum.PUBLISH.getValue()); } List calls = callRepository.findByStatusIn(callStatusList); return calls.stream() .map(this::convertToCallDetailsResponseBean) .collect(Collectors.toList()); } public CallResponse validateCallData(CallEntity callEntity) { validateUpdate(callEntity); CallResponse callResponseBean = getCallResponseBean(callEntity); FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId()); List formResponseBean = formDao.getFormsByCallId(callEntity.getId()); CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean); callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue()); callRepository.save(callEntity); callResponseBean.setCurrentStep(GepafinConstant.VALIDATE_REQUEST); callResponseBean.setStatus(CallStatusEnum.valueOf(callEntity.getStatus())); return callResponseBean; } public CallEntity getCallEntityById(Long id){ CallEntity callEntity=callRepository.findByIdAndStatusNotIn(id,List.of(CallStatusEnum.PUBLISH.getValue())); if(callEntity==null){ throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)); } return callEntity; } public CallResponse updateCallStatus(Long callId, CallStatusEnum statusReq) { CallEntity callEntity = validateCall(callId); CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus()); validateStatusChange(currentStatus, statusReq); callEntity.setStatus(statusReq.getValue()); callEntity = callRepository.save(callEntity); return convertToCallResponseBean(callEntity); } private void validateStatusChange(CallStatusEnum currentStatus, CallStatusEnum newStatus) { if (currentStatus == newStatus) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.STATUS_SAME_ERROR)); } switch (currentStatus) { case DRAFT: if (newStatus == CallStatusEnum.READY_TO_PUBLISH || newStatus == CallStatusEnum.PUBLISH) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_DRAFT)); } break; case PUBLISH: if (newStatus == CallStatusEnum.READY_TO_PUBLISH || newStatus == CallStatusEnum.DRAFT) { throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_PUBLISH)); } break; case EXPIRED: throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.STATUS_CANNOT_BE_CHANGED)); case READY_TO_PUBLISH: break; default: break; } } public CallEntity validatePublishedCall(Long callId) { CallEntity callEntity= callRepository .findByIdAndStatus(callId, CallStatusEnum.PUBLISH.getValue()); if(callEntity==null){ throw new ResourceNotFoundException( Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_PUBLISHED)); } LocalDate currentDate = LocalDate.now(); LocalTime currentTime = LocalTime.now(); if (currentDate.isBefore(callEntity.getStartDate().toLocalDate()) || (currentDate.isEqual(callEntity.getStartDate().toLocalDate()) && currentTime.isBefore(callEntity.getStartTime()))) { throw new CustomValidationException( Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.CALL_NOT_STARTED_YET) ); } if (currentDate.isAfter(callEntity.getEndDate().toLocalDate()) || (currentDate.isEqual(callEntity.getEndDate().toLocalDate()) && currentTime.isAfter(callEntity.getEndTime()))) { throw new CustomValidationException( Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.CALL_ALREADY_ENDED) ); } return callEntity; } }