Resolved conflicts
This commit is contained in:
@@ -105,12 +105,44 @@ public class ApplicationAmendmentRequestDao {
|
||||
@Autowired
|
||||
private AssignedApplicationsDao assignedApplicationsDao;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationDao applicationEvaluationDao;
|
||||
|
||||
@Autowired
|
||||
private DocumentRepository documentRepository;
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
public ApplicationAmendmentRequestResponse getApplicationDataForAmendment(Long applicationEvaluationId) {
|
||||
log.info("Fetching the application data for the Amendment process {}", applicationEvaluationId);
|
||||
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluation(applicationEvaluationId);
|
||||
Long applicationId = applicationEvaluationEntity.getApplicationId();
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
List<FieldRequest> evaluationFileRequests=new ArrayList<>();
|
||||
List<ChecklistRequest> checklistRequests=new ArrayList<>();
|
||||
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
String file=applicationEvaluationEntity.getFile();
|
||||
String checkList=applicationEvaluationEntity.getChecklist();
|
||||
if(file != null){
|
||||
evaluationFileRequests=Utils.convertJsonStringToList(file,FieldRequest.class);
|
||||
}
|
||||
Boolean allValid = evaluationFileRequests.stream()
|
||||
.anyMatch(fieldRequest -> fieldRequest.getValid() == null);
|
||||
if(checkList != null) {
|
||||
checklistRequests=Utils.convertJsonStringToList(checkList,ChecklistRequest.class);
|
||||
}
|
||||
boolean resultCheckList = checklistRequests.stream()
|
||||
.anyMatch(checklistRequest -> Boolean.TRUE.equals(checklistRequest.getValid())) ? false : true;
|
||||
|
||||
if(Boolean.TRUE.equals(allValid) || Boolean.TRUE.equals(resultCheckList)){
|
||||
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.All_DOCUMENT_CHECKED_AND_ONE_CHECKLIST_CHECKED));
|
||||
}
|
||||
// Set common application-level details
|
||||
String callName = application.getCall().getName();
|
||||
Long protocolNumber = (application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null)
|
||||
@@ -135,11 +167,18 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
List<ApplicationFormEntity> forms = applicationFormRepository.findByApplicationId(applicationId);
|
||||
List<AmendmentFormFieldResponse> allFormFields = new ArrayList<>();
|
||||
|
||||
Map<String, FieldRequest> fieldRequestMap = evaluationFileRequests.stream()
|
||||
.collect(Collectors.toMap(FieldRequest::getId, fieldRequest -> fieldRequest));
|
||||
for (ApplicationFormEntity form : forms) {
|
||||
String content = form.getForm().getContent();
|
||||
List<Map<String, Object>> result = filterByName(content, "fileupload");
|
||||
allFormFields.addAll(getIdAndLabelFromResult(result));
|
||||
List<AmendmentFormFieldResponse> amendmentFormFieldResponses= getIdAndLabelFromResult(result);
|
||||
amendmentFormFieldResponses.removeIf(amendmentFormFieldResponse -> {
|
||||
FieldRequest matchingRequest = fieldRequestMap.get(amendmentFormFieldResponse.getFieldId());
|
||||
// Remove if no matching FieldRequest exists or if valid is true
|
||||
return matchingRequest == null || Boolean.TRUE.equals(matchingRequest.getValid());
|
||||
});
|
||||
allFormFields.addAll(amendmentFormFieldResponses);
|
||||
}
|
||||
|
||||
response.setFormFields(allFormFields);
|
||||
@@ -200,7 +239,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
log.info("Submiting application data for amendment Process with details: {}", applicationEvaluationId);
|
||||
|
||||
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = createApplicationAmendmentRequestEntity(applicationAmendmentRequest, applicationEvaluationId);
|
||||
ApplicationAmendmentRequestResponse applicationAmendmentRequestResponse = convertEntityToResponse(applicationAmendmentRequestEntity);
|
||||
ApplicationAmendmentRequestResponse applicationAmendmentRequestResponse = convertEntityToResponse(applicationAmendmentRequestEntity,false);
|
||||
log.info("Application submitted successfully for amendment", applicationAmendmentRequestResponse);
|
||||
if (Boolean.TRUE.equals(applicationAmendmentRequestResponse.getIsSendEmail())) {
|
||||
emailNotificationDao.sendMailToNotifyBeneficiaryRegardingNewAmendment(applicationAmendmentRequestEntity);
|
||||
@@ -237,6 +276,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
AmendmentFormField formField = new AmendmentFormField();
|
||||
formField.setFieldId(amendmentFormFieldRequest.getFieldId());
|
||||
formField.setFieldValue(null);
|
||||
formField.setLabel(amendmentFormFieldRequest.getLabel());
|
||||
return formField;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
@@ -261,7 +301,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
Long protocolNumber = protocolDao.getProtocolNumber(userEntity.getHub());
|
||||
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(
|
||||
applicationEvaluationEntity.getAssignedApplicationsEntity().getApplication(), protocolNumber,
|
||||
userEntity.getHub().getId());
|
||||
userEntity.getHub().getId(),false);
|
||||
applicationAmendmentRequestEntity.setProtocol(protocolEntity);
|
||||
ApplicationAmendmentRequestEntity applicationAmendment = saveApplicationAmendmentRequestEntity(applicationAmendmentRequestEntity, null, VersionActionTypeEnum.INSERT);
|
||||
String evaluationStatusType = applicationEvaluationEntity.getStatus();
|
||||
@@ -294,6 +334,10 @@ public class ApplicationAmendmentRequestDao {
|
||||
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.SOCCORSO.getValue());
|
||||
assignedApplicationsRepository.save(assignedApplicationsEntity);
|
||||
|
||||
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(applicationEntity, NotificationTypeEnum.AMENDMENT_CREATION);
|
||||
|
||||
notificationDao.sendNotificationToInstructor(placeHolders,applicationAmendmentRequestEntity.getApplicationEvaluationEntity(),NotificationTypeEnum.AMENDMENT_CREATION);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update Assigned Application" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplication).newData(assignedApplicationsEntity).build());
|
||||
}
|
||||
@@ -301,6 +345,25 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
return applicationAmendment;
|
||||
}
|
||||
private void setAmendmentDocuments(String amendmentNotes, String amendmentFieldRequest,
|
||||
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity) {
|
||||
AmendmentDetailsResponseBean amendmentDetails = new AmendmentDetailsResponseBean();
|
||||
if (amendmentFieldRequest != null && !amendmentFieldRequest.trim().isEmpty()) {
|
||||
String[] documentIds = amendmentFieldRequest.split(",");
|
||||
String validDocumentIds = Arrays.stream(documentIds)
|
||||
.map(String::trim)
|
||||
.filter(id -> !id.isEmpty())
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
amendmentDetails.setAmendmentDocuments(validDocumentIds);
|
||||
}
|
||||
if (amendmentNotes != null && !amendmentNotes.trim().isEmpty()) {
|
||||
amendmentDetails.setAmendmentNotes(amendmentNotes.trim());
|
||||
}
|
||||
amendmentDetails.setValid(null);
|
||||
String amendmentDetailsJson = Utils.convertObjectToString(amendmentDetails);
|
||||
applicationAmendmentRequestEntity.setAmendmentDocument(amendmentDetailsJson);
|
||||
}
|
||||
|
||||
public ApplicationAmendmentRequestEntity saveApplicationAmendmentRequestEntity(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity,ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity,VersionActionTypeEnum actionTypeEnum) {
|
||||
ApplicationAmendmentRequestEntity applicationAmendmentRequest = applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
|
||||
@@ -311,23 +374,81 @@ public class ApplicationAmendmentRequestDao {
|
||||
return applicationAmendmentRequest;
|
||||
}
|
||||
|
||||
public ApplicationAmendmentRequestResponse convertEntityToResponse(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity) {
|
||||
ApplicationAmendmentRequestResponse response = initializeBasicResponse(applicationAmendmentRequestEntity);
|
||||
public ApplicationAmendmentRequestResponse convertEntityToResponse(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity,boolean includeEmailContent) {
|
||||
ApplicationAmendmentRequestResponse response = initializeBasicResponse(applicationAmendmentRequestEntity,includeEmailContent);
|
||||
|
||||
List<ApplicationFormEntity> forms = applicationFormRepository.findByApplicationId(applicationAmendmentRequestEntity.getApplicationId());
|
||||
Map<String, String> fieldIdToLabelMap = extractFieldIdToLabelMap(forms);
|
||||
|
||||
// List<AmendmentFieldRequest> amendmentFieldRequests= new ArrayList<>();
|
||||
List<AmendmentFormField> amendmentFormFields = Utils.convertJsonStringToList(
|
||||
applicationAmendmentRequestEntity.getFormFields(), AmendmentFormField.class);
|
||||
Map<String, ApplicationFormFieldEntity> formFieldEntityMap = getApplicationFormFieldEntityMap(applicationAmendmentRequestEntity, amendmentFormFields);
|
||||
if (applicationAmendmentRequestEntity.getAmendmentDocument() != null) {
|
||||
|
||||
// List<AmendmentDetailsResponseBean> amendmentDetailsList =
|
||||
// Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getAmendmentDocument(),
|
||||
// AmendmentDetailsResponseBean.class);
|
||||
AmendmentDetailsResponseBean amendmentDetails = Utils.convertStringToObject(applicationAmendmentRequestEntity.getAmendmentDocument() ,AmendmentDetailsResponseBean.class);
|
||||
if(amendmentDetails!=null) {
|
||||
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
|
||||
if (amendmentDetails.getAmendmentDocuments() != null) {
|
||||
// Extract the comma-separated document IDs as a string
|
||||
String documentIdsString = amendmentDetails.getAmendmentDocuments();
|
||||
|
||||
if (documentIdsString != null && !documentIdsString.trim().isEmpty()) {
|
||||
// Split the comma-separated values and process them
|
||||
List<String> documentIds = Arrays.stream(documentIdsString.split(","))
|
||||
.map(String::trim)
|
||||
.filter(id -> !id.isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
documentResponseBeans.addAll(
|
||||
documentIds.stream()
|
||||
.map(id -> {
|
||||
try {
|
||||
return createDocumentResponseBean(id); // Convert to Long
|
||||
} catch (NumberFormatException e) {
|
||||
// Handle invalid document IDs gracefully
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull) // Skip null responses
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
response.setAmendmentNotes(amendmentDetails.getAmendmentNotes());
|
||||
response.setValid(amendmentDetails.getValid());
|
||||
}
|
||||
}
|
||||
response.setAmendmentDocuments(documentResponseBeans);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
processFormFields(amendmentFormFields, fieldIdToLabelMap, formFieldEntityMap, response);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private ApplicationAmendmentRequestResponse initializeBasicResponse(ApplicationAmendmentRequestEntity entity) {
|
||||
public DocumentResponseBean createDocumentResponseBean(String documentId) {
|
||||
|
||||
if (!StringUtils.isEmpty(documentId)) {
|
||||
Optional<DocumentEntity> documentEntity = documentRepository.findByIdAndNotDeleted(Long.valueOf(documentId));
|
||||
if(documentEntity.isPresent()){
|
||||
return applicationEvaluationDao.createDocumentResponseBean(documentEntity.get());
|
||||
}}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private ApplicationAmendmentRequestResponse initializeBasicResponse(ApplicationAmendmentRequestEntity entity,boolean includeEmailContent) {
|
||||
ApplicationAmendmentRequestResponse response = new ApplicationAmendmentRequestResponse();
|
||||
ApplicationEntity applicationEntity = entity.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication();
|
||||
Long hubId = applicationEntity.getHubId();
|
||||
HubEntity hubEntity = hubService.valdateHub(hubId);
|
||||
|
||||
response.setId(entity.getId());
|
||||
response.setApplicationId(entity.getApplicationId());
|
||||
response.setApplicationEvaluationId(entity.getApplicationEvaluationEntity().getId());
|
||||
@@ -349,10 +470,17 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
UserEntity userEntity = userService.validateUser(application.getUserId());
|
||||
response.setBeneficiaryName(buildBeneficiaryName(userEntity));
|
||||
|
||||
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
|
||||
response.setCompanyName(company.getCompanyName());
|
||||
Long protocolNumber = entity.getProtocol() != null ? entity.getProtocol().getProtocolNumber() : null;
|
||||
response.setProtocolNumber(protocolNumber);
|
||||
|
||||
if (includeEmailContent) {
|
||||
Map<String, String> bodyPlaceholders = emailNotificationDao.prepareEmailPlaceholders(applicationEntity, entity);
|
||||
EmailContentResponse emailContent = emailNotificationDao.prepareEmailContent(applicationEntity, SystemEmailTemplatesEntityTypeEnum.DOCUMENTATION_INTEGRATION_REQUEST, hubEntity, bodyPlaceholders);
|
||||
String body = emailContent.getBody();
|
||||
response.setEmailTemplate(body);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -397,6 +525,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
return responseBean;
|
||||
})
|
||||
.toList();
|
||||
@@ -458,7 +587,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
public ApplicationAmendmentRequestResponse getApplicationAmendmentRequestById(Long id) {
|
||||
log.info("Fetching application amendment with ID: {}", id);
|
||||
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(applicationAmendmentRequestEntity);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(applicationAmendmentRequestEntity,true);
|
||||
log.info("Application Amendment fetched successfully by ID: {}", response);
|
||||
return response;
|
||||
}
|
||||
@@ -475,7 +604,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
applicationAmendmentRequestRepository.findAll(spec);
|
||||
|
||||
return applicationAmendmentRequestEntities.stream()
|
||||
.map(this::convertEntityToResponse)
|
||||
.map(entity -> convertEntityToResponse(entity, false))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -498,6 +627,20 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
log.info("Updating application amendement with ID: {}", id);
|
||||
ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
|
||||
Boolean isBeneficiary=false;
|
||||
if (Boolean.FALSE.equals(validator.checkIsBeneficiary())) {
|
||||
validator.validatePreInstructor(request, existingApplicationAmendment.getApplicationEvaluationEntity().getUserId());
|
||||
isBeneficiary=false;
|
||||
} else {
|
||||
validator.validateUserId(request, existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getUserId());
|
||||
isBeneficiary=true;
|
||||
}
|
||||
if(Boolean.TRUE.equals(isBeneficiary) && existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue())){
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
if(Boolean.FALSE.equals(isBeneficiary) && existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.AWAITING.getValue())){
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
|
||||
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment);
|
||||
setIfUpdated(existingApplicationAmendment::getNote, existingApplicationAmendment::setNote, updateRequest.getNote());
|
||||
@@ -510,16 +653,18 @@ public class ApplicationAmendmentRequestDao {
|
||||
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);
|
||||
// ApplicationFormFieldEntity applicationFormFieldEntity = getApplicationFormField(applicationFormFieldMap, applicationFormFieldRequest.getFieldId());
|
||||
// updateApplicationFormField(applicationFormFieldEntity,applicationFormFieldRequest, amendmentFormField);
|
||||
updateFormField(applicationFormFieldRequest, amendmentFormField);
|
||||
});
|
||||
existingApplicationAmendment.setFormFields(Utils.convertListToJsonString(amendmentFormFieldMap.values().stream().toList()));
|
||||
}
|
||||
existingApplicationAmendment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
|
||||
if(updateRequest.getAmendmentDocuments()!=null && Boolean.FALSE.equals(updateRequest.getAmendmentDocuments().isEmpty())) {
|
||||
setAmendmentDocuments(updateRequest.getAmendmentNotes(),updateRequest.getAmendmentDocuments(), existingApplicationAmendment);
|
||||
}
|
||||
ApplicationAmendmentRequestEntity updatedApplicationAmendment = saveApplicationAmendmentRequestEntity(existingApplicationAmendment,oldApplicationAmendmentEntity,VersionActionTypeEnum.UPDATE);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment,false);
|
||||
log.info("Application Amendment updated successfully: {}", response);
|
||||
return response;
|
||||
}
|
||||
@@ -584,13 +729,13 @@ public class ApplicationAmendmentRequestDao {
|
||||
String fieldId) {
|
||||
AmendmentFormField amendmentFormField = amendmentFormFieldMap.get(fieldId);
|
||||
if (amendmentFormField == null) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, GepafinConstant.APPLICATION_FORM_FIELD_NOT_FOUND);
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_FORM_FIELD_NOT_FOUND));
|
||||
}
|
||||
return amendmentFormField;
|
||||
}
|
||||
|
||||
|
||||
private void updateFormField(ApplicationFormFieldRequestBean applicationFormFieldRequest,
|
||||
private void updateFormField(AmendmentFormFieldRequest applicationFormFieldRequest,
|
||||
AmendmentFormField amendmentFormField) {
|
||||
List<Long> requestedDocumentIds = extractIds(applicationFormFieldRequest.getFieldValue());
|
||||
List<Long> existingDocumentIds = extractIds(amendmentFormField.getFieldValue());
|
||||
@@ -599,7 +744,8 @@ public class ApplicationAmendmentRequestDao {
|
||||
if (!existingDocumentIds.isEmpty()) {
|
||||
existingDocumentIds.forEach(this::softDeleteDocument);
|
||||
amendmentFormField.setFieldValue(null);
|
||||
setIsUploadedBy(amendmentFormField);
|
||||
amendmentFormField.setValid(applicationFormFieldRequest.getValid());
|
||||
// setIsUploadedBy(amendmentFormField);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -613,11 +759,12 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
if (!newFieldValue.equals(amendmentFormField.getFieldValue())) {
|
||||
amendmentFormField.setFieldValue(newFieldValue);
|
||||
setIsUploadedBy(amendmentFormField);
|
||||
amendmentFormField.setValid(applicationFormFieldRequest.getValid());
|
||||
// setIsUploadedBy(amendmentFormField);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Long> extractIds(Object fieldValue) {
|
||||
public List<Long> extractIds(Object fieldValue) {
|
||||
if (fieldValue instanceof String && !StringUtils.isEmpty((String) fieldValue)) {
|
||||
return Arrays.stream(((String) fieldValue).split(","))
|
||||
.map(Long::valueOf)
|
||||
@@ -628,14 +775,14 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
|
||||
|
||||
private void setIsUploadedBy(AmendmentFormField amendmentFormField) {
|
||||
if(validator.checkIsBeneficiary()) {
|
||||
amendmentFormField.setIsUploadedBy(AmendmentFormField.AmendmentIsUploadedByEnum.BENEFICIARY.getValue());
|
||||
}else {
|
||||
amendmentFormField.setIsUploadedBy(AmendmentFormField.AmendmentIsUploadedByEnum.PRE_INSTRUCTOR.getValue());
|
||||
}
|
||||
|
||||
}
|
||||
// private void setIsUploadedBy(AmendmentFormField amendmentFormField) {
|
||||
// if(validator.checkIsBeneficiary()) {
|
||||
// amendmentFormField.setIsUploadedBy(AmendmentFormField.AmendmentIsUploadedByEnum.BENEFICIARY.getValue());
|
||||
// }else {
|
||||
// amendmentFormField.setIsUploadedBy(AmendmentFormField.AmendmentIsUploadedByEnum.PRE_INSTRUCTOR.getValue());
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
|
||||
// private void updateApplicationFormFields(ApplicationAmendmentRequestEntity applicationAmendment, ApplicationFormFieldRequestBean updatedFormField) {
|
||||
@@ -818,7 +965,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
applicationAmendmentRequestRepository.findByUserId(beneficiaryUserId);
|
||||
|
||||
return entities.stream()
|
||||
.map(this::convertEntityToResponse)
|
||||
.map(entity -> convertEntityToResponse(entity, false))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -828,8 +975,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
|
||||
//cloned entity for old data and versioning
|
||||
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment);
|
||||
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequestList = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequestList = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
|
||||
existingApplicationAmendment.getApplicationEvaluationEntity().getId()
|
||||
);
|
||||
|
||||
@@ -847,7 +993,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
ApplicationAmendmentRequestEntity updatedApplicationAmendment = saveApplicationAmendmentRequestEntity(existingApplicationAmendment, oldApplicationAmendmentEntity,
|
||||
VersionActionTypeEnum.UPDATE);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment,false);
|
||||
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequests = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
|
||||
existingApplicationAmendment.getApplicationEvaluationEntity().getId());
|
||||
@@ -874,6 +1020,11 @@ public class ApplicationAmendmentRequestDao {
|
||||
AssignedApplicationsEntity oldAssignedApplicationData = Utils.getClonedEntityForData(assignedApplicationsEntity);
|
||||
assignedApplicationsEntity = assignedApplicationsRepository.save(existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity());
|
||||
|
||||
|
||||
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.AMENDMENT_CLOSED);
|
||||
|
||||
notificationDao.sendNotificationToInstructor(placeHolders,existingApplicationAmendment.getApplicationEvaluationEntity(),NotificationTypeEnum.AMENDMENT_CLOSED);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update Application Evaluation" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluationEntity)
|
||||
.newData(existingApplicationEvaluationEntity).build());
|
||||
@@ -893,6 +1044,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
public ApplicationAmendmentRequestResponse extendResponseDays(Long id, Long newResponseDays) {
|
||||
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
|
||||
|
||||
@@ -906,7 +1058,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
/** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationAmendmentEntity).newData(applicationAmendmentRequestEntity).build());
|
||||
}
|
||||
return convertEntityToResponse(applicationAmendmentRequestEntity);
|
||||
return convertEntityToResponse(applicationAmendmentRequestEntity,false);
|
||||
}
|
||||
|
||||
public List<ApplicationAmendmentRequestResponse> getAmendmentByApplicationId(HttpServletRequest request, Long applicationId, List<ApplicationAmendmentRequestEnum> statuses) {
|
||||
@@ -931,7 +1083,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
List<ApplicationAmendmentRequestResponse> response = new ArrayList<>();
|
||||
if (applicationAmendmentRequestEntity != null) {
|
||||
response = applicationAmendmentRequestEntity.stream()
|
||||
.map(this::convertEntityToResponse)
|
||||
.map(entity -> convertEntityToResponse(entity, false))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
return response;
|
||||
@@ -943,7 +1095,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
log.info("Updating application amendment with status: {}", id);
|
||||
ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
|
||||
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment);
|
||||
if (Boolean.TRUE.equals(existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.AWAITING.getValue())) || Boolean.TRUE.equals(statusTypeEnum.equals(ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED))) {
|
||||
if (Boolean.TRUE.equals(existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.AWAITING.getValue())) && Boolean.TRUE.equals(statusTypeEnum.equals(ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED))) {
|
||||
existingApplicationAmendment.setStatus(ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue());
|
||||
existingApplicationAmendment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
applicationAmendmentRequestRepository.save(existingApplicationAmendment);
|
||||
@@ -951,7 +1103,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
/** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationAmendmentEntity).newData(existingApplicationAmendment).build());
|
||||
}
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(existingApplicationAmendment);
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(existingApplicationAmendment,false);
|
||||
log.info("Amendment status updated successfully: {}", response);
|
||||
return response;
|
||||
}
|
||||
@@ -1027,12 +1179,6 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
|
||||
}
|
||||
public List<ApplicationAmendmentRequestEntity> getApplicationAmendmentRequestEntitiesByApplicationEvaluationId(Long applicationEvaluationId){
|
||||
List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities=new ArrayList<>();
|
||||
applicationAmendmentRequestEntities=applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(applicationEvaluationId,ApplicationAmendmentRequestEnum.CLOSE.getValue());
|
||||
return applicationAmendmentRequestEntities;
|
||||
}
|
||||
|
||||
private void softDeleteDocument(Long documentId) {
|
||||
documentService.deleteFile(documentId);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBea
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationRequestBean;
|
||||
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
|
||||
import net.gepafin.tendermanagement.model.request.NotificationReq;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.model.response.*;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
import net.gepafin.tendermanagement.service.AmazonS3Service;
|
||||
import net.gepafin.tendermanagement.service.ApplicationEvaluationService;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import net.gepafin.tendermanagement.service.DocumentService;
|
||||
@@ -159,7 +161,22 @@ public class ApplicationDao {
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private TokenProvider tokenProvider;
|
||||
private ApplicationEvaluationService applicationEvaluationService;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private RoleRepository roleRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestRepository applicationAmendmentRequestRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
|
||||
FormEntity formEntity = formService.validateForm(formId);
|
||||
@@ -386,6 +403,16 @@ public class ApplicationDao {
|
||||
responseBean.setStatus(applicationEntity.getStatus());
|
||||
responseBean.setComments(applicationEntity.getComments());
|
||||
responseBean.setCompanyId(applicationEntity.getCompanyId());
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId());
|
||||
if(assignedApplicationsOptional.isPresent()){
|
||||
responseBean.setAssignedUserId(assignedApplicationsOptional.get().getUserId());
|
||||
UserEntity user = userService.validateUser(assignedApplicationsOptional.get().getUserId());
|
||||
String firstName = user.getFirstName() != null ? user.getFirstName() : "";
|
||||
String lastName = user.getLastName() != null ? user.getLastName() : "";
|
||||
String userName = String.join(" ", firstName, lastName).trim();
|
||||
responseBean.setAssignedUserName(userName);
|
||||
}
|
||||
CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
|
||||
responseBean.setCompanyName(company.getCompanyName());
|
||||
if(applicationEntity.getProtocol() != null) {
|
||||
@@ -458,7 +485,7 @@ public class ApplicationDao {
|
||||
if (applicationFormFieldEntity1.getFieldId().equals(applicationFormFieldRequestBean.getFieldId())) {
|
||||
applicationFormFieldEntity = applicationFormFieldEntity1;
|
||||
oldApplicationFormFieldData = Utils.getClonedEntityForData(applicationFormFieldEntity);
|
||||
if (applicationFormEntity.getForm().getId().equals(applicationFormEntity.getApplication().getCall().getInitialForm())) {
|
||||
if (applicationFormEntity.getForm().getId().equals(applicationFormEntity.getApplication().getCall().getInitialForm()) && checkIfRequestFieldIsDifferent(applicationFormFieldEntity1, applicationFormFieldRequestBean)) {
|
||||
validateRequiredFields(applicationFormEntity.getForm(), applicationFormEntity.getApplication(), applicationFormFieldRequestBean.getFieldId());
|
||||
}
|
||||
actionType = VersionActionTypeEnum.UPDATE;
|
||||
@@ -494,7 +521,30 @@ public class ApplicationDao {
|
||||
return applicationFormField;
|
||||
}
|
||||
|
||||
void updateDocumentDeletionStatus(ApplicationFormFieldEntity applicationFormFieldEntity, ApplicationFormFieldRequestBean applicationFormFieldRequestBean, FormEntity formEntity, List<Long> newDocumentIds,
|
||||
private Boolean checkIfRequestFieldIsDifferent(ApplicationFormFieldEntity applicationFormFieldEntity,
|
||||
ApplicationFormFieldRequestBean applicationFormFieldRequestBean) {
|
||||
|
||||
// Retrieve the field values from both objects
|
||||
String entityFieldValue = applicationFormFieldEntity.getFieldValue();
|
||||
Object requestFieldValue = applicationFormFieldRequestBean.getFieldValue();
|
||||
|
||||
// Check if both are null
|
||||
if (entityFieldValue == null && requestFieldValue == null) {
|
||||
return false; // No difference if both are null
|
||||
}
|
||||
|
||||
// Compare values
|
||||
Boolean check = !Objects.equals(entityFieldValue, requestFieldValue);
|
||||
|
||||
// Additional comparison if both are non-null
|
||||
if (Boolean.TRUE.equals(check) && entityFieldValue != null && requestFieldValue != null) {
|
||||
check = !entityFieldValue.equals(requestFieldValue.toString());
|
||||
}
|
||||
|
||||
return check;
|
||||
}
|
||||
|
||||
void updateDocumentDeletionStatus(ApplicationFormFieldEntity applicationFormFieldEntity, ApplicationFormFieldRequestBean applicationFormFieldRequestBean, FormEntity formEntity, List<Long> newDocumentIds,
|
||||
List<String> preInstructorDocumentId,boolean isPreInstructor) {
|
||||
if (newDocumentIds == null) {
|
||||
newDocumentIds = Collections.emptyList();
|
||||
@@ -780,18 +830,18 @@ public class ApplicationDao {
|
||||
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyEntity.getId());
|
||||
|
||||
// call = callService.validatePublishedCall(call.getId());
|
||||
checkIfApplicationExists(call, userWithCompanyEntity, userEntity);
|
||||
// checkIfApplicationExists(call, userWithCompanyEntity, userEntity);
|
||||
ApplicationEntity applicationEntity = createApplicationEntity(userEntity, call, userWithCompanyEntity);
|
||||
applicationEntity.setComments(applicationRequest.getComments());
|
||||
applicationEntity = saveApplicationEntity(applicationEntity);
|
||||
return getApplicationResponse(applicationEntity);
|
||||
}
|
||||
public void checkIfApplicationExists(CallEntity call, UserWithCompanyEntity userWithCompanyEntity, UserEntity userEntity){
|
||||
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByUserIdAndUserWithCompanyIdAndCallIdAndIsDeletedFalse(userEntity.getId(), userWithCompanyEntity.getId(),call.getId());
|
||||
if(applicationEntity.isPresent()){
|
||||
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
|
||||
}
|
||||
}
|
||||
// public void checkIfApplicationExists(CallEntity call, UserWithCompanyEntity userWithCompanyEntity, UserEntity userEntity){
|
||||
// Optional<ApplicationEntity> applicationEntity=applicationRepository.findByUserIdAndUserWithCompanyIdAndCallIdAndIsDeletedFalse(userEntity.getId(), userWithCompanyEntity.getId(),call.getId());
|
||||
// if(applicationEntity.isPresent()){
|
||||
// throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
|
||||
// }
|
||||
// }
|
||||
|
||||
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
|
||||
|
||||
@@ -812,11 +862,13 @@ public class ApplicationDao {
|
||||
if (status.equals(ApplicationStatusTypeEnum.SUBMIT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
|
||||
callService.validatePublishedCall(applicationEntity.getCall().getId(), userEntity.getHub().getId());
|
||||
Long protocolNumber = protocolDao.getProtocolNumber(userEntity.getHub());
|
||||
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId());
|
||||
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true);
|
||||
applicationEntity.setProtocol(protocolEntity);
|
||||
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
|
||||
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
applicationEntity = applicationRepository.save(applicationEntity);
|
||||
Map<String ,String> placeHolders=notificationDao.sendNotificationToBeneficiary(applicationEntity,NotificationTypeEnum.APPLICATION_SUBMISSION);
|
||||
notificationDao.sendNotificationToSuperUser(applicationEntity,placeHolders,NotificationTypeEnum.APPLICATION_SUBMISSION);
|
||||
|
||||
/** This code is responsible for adding a version history log for "Update application status" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
@@ -829,6 +881,9 @@ public class ApplicationDao {
|
||||
if (status.equals(ApplicationStatusTypeEnum.DRAFT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.AWAITING.getValue()))) {
|
||||
applicationEntity.setStatus(status.getValue());
|
||||
}
|
||||
if(status.equals(ApplicationStatusTypeEnum.ADMISSIBLE) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.APPOINTMENT.getValue()))){
|
||||
applicationEntity.setStatus(status.getValue());
|
||||
}
|
||||
applicationEntity = applicationRepository.save(applicationEntity);
|
||||
|
||||
if (!status.equals(ApplicationStatusTypeEnum.SUBMIT)) {
|
||||
@@ -1110,7 +1165,14 @@ public class ApplicationDao {
|
||||
public ApplicationSignedDocumentResponse getSignedDocument(HttpServletRequest request, Long applicationId) {
|
||||
|
||||
ApplicationEntity applicationEntity = validateApplication(applicationId);
|
||||
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
|
||||
// validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
|
||||
|
||||
if (validator.checkIsPreInstructor()) {
|
||||
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluationByApplicationId(applicationId);
|
||||
validator.validatePreInstructor(request, applicationEvaluationEntity.getUserId());
|
||||
} else {
|
||||
validator.validateUserId(request, applicationEntity.getUserId());
|
||||
}
|
||||
|
||||
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
|
||||
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
|
||||
@@ -1169,90 +1231,121 @@ public class ApplicationDao {
|
||||
}
|
||||
|
||||
public byte[] downloadApplicationDocumentsAsZip(HttpServletRequest request, Long applicationId) {
|
||||
|
||||
ApplicationEntity applicationEntity = validateApplication(applicationId);
|
||||
validateAssignedUser(request, applicationId);
|
||||
|
||||
Set<Long> documentIds = extractDocumentIdsFromApplicationForms(applicationId);
|
||||
List<DocumentEntity> documents = documentRepository.findAllByIdInAndIsDeletedFalse(documentIds);
|
||||
|
||||
ApplicationSignedDocumentEntity signedDocument = applicationSignedDocumentRepository
|
||||
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
|
||||
if (documents.isEmpty() && signedDocument == null) {
|
||||
ApplicationSignedDocumentEntity signedDocument = applicationSignedDocumentRepository.findByApplicationIdAndStatus(applicationId,
|
||||
ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
|
||||
List<DocumentEntity> amendmentDocuments = fetchAmendmentDocuments(applicationId);
|
||||
List<DocumentEntity> evaluationDocuments = fetchEvaluationDocuments(applicationId);
|
||||
if (documents.isEmpty() && signedDocument == null && amendmentDocuments.isEmpty() && evaluationDocuments.isEmpty()) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
|
||||
}
|
||||
return createZipWithDocuments(applicationEntity, documents, signedDocument, applicationId);
|
||||
return createZipWithDocuments(applicationEntity, documents, signedDocument, amendmentDocuments, evaluationDocuments, applicationId);
|
||||
}
|
||||
|
||||
private void validateAssignedUser(HttpServletRequest request, Long applicationId) {
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository
|
||||
.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
|
||||
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
|
||||
if (assignedApplications != null) {
|
||||
validator.validatePreInstructor(request, assignedApplications.getUserId());
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> extractDocumentIdsFromApplicationForms(Long applicationId) {
|
||||
|
||||
Set<Long> documentIds = new HashSet<>();
|
||||
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationId);
|
||||
|
||||
applicationForms.forEach(applicationForm -> {
|
||||
FormEntity formEntity = applicationForm.getForm();
|
||||
if (formEntity != null) {
|
||||
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
|
||||
contentResponseBeans.stream()
|
||||
.filter(content -> "fileupload".equals(content.getName()))
|
||||
.forEach(content -> {
|
||||
Optional<ApplicationFormFieldEntity> formField = applicationFormFieldRepository
|
||||
.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
|
||||
content.getId(), applicationForm.getId(), applicationId);
|
||||
formField.ifPresent(field -> {
|
||||
if (field.getFieldValue() != null) {
|
||||
Arrays.stream(field.getFieldValue().split(","))
|
||||
.map(String::trim)
|
||||
.map(Long::valueOf)
|
||||
.forEach(documentIds::add);
|
||||
}
|
||||
});
|
||||
});
|
||||
contentResponseBeans.stream().filter(content -> "fileupload".equals(content.getName())).forEach(content -> {
|
||||
Optional<ApplicationFormFieldEntity> formField = applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
|
||||
content.getId(), applicationForm.getId(), applicationId);
|
||||
formField.ifPresent(field -> {
|
||||
if (field.getFieldValue() != null) {
|
||||
Arrays.stream(field.getFieldValue().split(",")).map(String::trim).map(Long::valueOf).forEach(documentIds::add);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
return documentIds;
|
||||
}
|
||||
|
||||
private void addDocumentToZip(ZipOutputStream zos, String s3Folder, String filePath, String fileName) {
|
||||
private List<DocumentEntity> fetchAmendmentDocuments(Long applicationId) {
|
||||
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequests = applicationAmendmentRequestRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
|
||||
Set<Long> amendmentIds = amendmentRequests.stream().map(ApplicationAmendmentRequestEntity::getId).collect(Collectors.toSet());
|
||||
return documentRepository.findBySourceIdInAndSourceAndIsDeletedFalse(amendmentIds, DocumentSourceTypeEnum.AMENDMENT.getValue());
|
||||
}
|
||||
private List<DocumentEntity> fetchEvaluationDocuments(Long applicationId) {
|
||||
|
||||
Optional<ApplicationEvaluationEntity> evaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
|
||||
if (evaluationEntity.isPresent()) {
|
||||
Long evaluationId = evaluationEntity.get().getId();
|
||||
return documentRepository.findBySourceIdInAndSourceAndIsDeletedFalse(Collections.singleton(evaluationId), DocumentSourceTypeEnum.EVALUATION.getValue());
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
private String fetchProtocolNumberForAmendment(Long amendmentRequestId) {
|
||||
|
||||
ApplicationAmendmentRequestEntity amendmentRequest = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(amendmentRequestId).orElse(null);
|
||||
if (amendmentRequest != null && amendmentRequest.getProtocol() != null) {
|
||||
return amendmentRequest.getProtocol().getProtocolNumber().toString();
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
private void addDocumentToZip(ZipOutputStream zos, String s3Folder, String filePath, String fullPath) {
|
||||
|
||||
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, filePath)) {
|
||||
zos.putNextEntry(new ZipEntry(fileName));
|
||||
zos.putNextEntry(new ZipEntry(fullPath));
|
||||
IOUtils.copy(fileInputStream, zos);
|
||||
zos.closeEntry();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error downloading or adding document to ZIP: " + fileName, e);
|
||||
throw new RuntimeException("Error downloading or adding document to ZIP: " + fullPath, e);
|
||||
}
|
||||
}
|
||||
private byte[] createZipWithDocuments(ApplicationEntity applicationEntity, List<DocumentEntity> documents, ApplicationSignedDocumentEntity signedDocument,
|
||||
List<DocumentEntity> amendmentDocuments, List<DocumentEntity> evaluationDocuments, Long applicationId) {
|
||||
|
||||
private byte[] createZipWithDocuments(ApplicationEntity applicationEntity, List<DocumentEntity> documents,
|
||||
ApplicationSignedDocumentEntity signedDocument, Long applicationId) {
|
||||
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
|
||||
String s3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION, applicationEntity.getCall().getId(), applicationId,0L);
|
||||
|
||||
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
Long callId = applicationEntity.getCall().getId();
|
||||
// Add Application Documents
|
||||
String appS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION, callId, applicationId, 0L);
|
||||
for (DocumentEntity document : documents) {
|
||||
String fileName = Utils.extractFileName(document.getFilePath());
|
||||
addDocumentToZip(zos, s3Folder, document.getFilePath(), fileName);
|
||||
addDocumentToZip(zos, appS3Folder, document.getFilePath(), fileName);
|
||||
}
|
||||
|
||||
// Add Signed Document
|
||||
if (signedDocument != null) {
|
||||
String signedDocS3Folder = s3PathConfig.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, applicationEntity.getCall().getId(), applicationId,0L);
|
||||
String signedDocFileName = signedDocument.getFileName();
|
||||
addDocumentToZip(zos, signedDocS3Folder, signedDocument.getFilePath(), signedDocFileName);
|
||||
String signedFolder = "SIGNED_DOCUMENT/";
|
||||
String signedDocS3Folder = s3PathConfig.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId, 0L);
|
||||
String fileName = signedDocument.getFileName();
|
||||
addDocumentToZip(zos, signedDocS3Folder, signedDocument.getFilePath(), signedFolder + fileName);
|
||||
}
|
||||
// Add Amendment (Soccorso) Documents
|
||||
for (DocumentEntity amendmentDocument : amendmentDocuments) {
|
||||
String protocolNumber = fetchProtocolNumberForAmendment(amendmentDocument.getSourceId());
|
||||
String amendmentFolder = "SOCCORSO_" + protocolNumber + "/";
|
||||
String amendmentS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.AMENDMENT, callId, applicationId, amendmentDocument.getSourceId());
|
||||
String fileName = Utils.extractFileName(amendmentDocument.getFilePath());
|
||||
addDocumentToZip(zos, amendmentS3Folder, amendmentDocument.getFilePath(), amendmentFolder + fileName);
|
||||
}
|
||||
// Add Evaluation Documents
|
||||
for (DocumentEntity evaluationDocument : evaluationDocuments) {
|
||||
String evaluationFolder = "EVALUATION/";
|
||||
String evaluationS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.EVALUATION, callId, applicationId, evaluationDocument.getSourceId());
|
||||
String fileName = Utils.extractFileName(evaluationDocument.getFilePath());
|
||||
addDocumentToZip(zos, evaluationS3Folder, evaluationDocument.getFilePath(), evaluationFolder + fileName);
|
||||
}
|
||||
|
||||
zos.finish();
|
||||
return zipOutputStream.toByteArray();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error while creating ZIP file", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
@@ -12,25 +11,25 @@ import net.gepafin.tendermanagement.enums.*;
|
||||
import net.gepafin.tendermanagement.model.request.*;
|
||||
import net.gepafin.tendermanagement.model.response.*;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import net.gepafin.tendermanagement.service.AssignedApplicationsService;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
import net.gepafin.tendermanagement.service.*;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
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.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
|
||||
import static org.apache.commons.lang3.StringUtils.isNumeric;
|
||||
|
||||
@Component
|
||||
public class ApplicationEvaluationDao {
|
||||
@@ -93,6 +92,24 @@ public class ApplicationEvaluationDao {
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Autowired
|
||||
private DocumentService documentService;
|
||||
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestDao applicationAmendmentRequestDao;
|
||||
|
||||
private ApplicationEvaluationEntity convertToEntity(UserEntity user, ApplicationEvaluationRequest req, Long assignedApplciationId) {
|
||||
|
||||
ApplicationEvaluationEntity entity = new ApplicationEvaluationEntity();
|
||||
@@ -112,7 +129,7 @@ public class ApplicationEvaluationDao {
|
||||
entity.setRemainingDays(30L);
|
||||
entity.setSuspendedDays(0L);
|
||||
entity.setStartDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
entity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now().plusDays(30)));
|
||||
entity.setEndDate(DateTimeUtil.DateServerToUTC(application.getSubmissionDate().plusDays(30)));
|
||||
entity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
|
||||
return entity;
|
||||
}
|
||||
@@ -128,16 +145,103 @@ public class ApplicationEvaluationDao {
|
||||
List<CallTargetAudienceChecklistEntity> checklistEntities = callTargetAudienceChecklistRepository
|
||||
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue());
|
||||
List<ApplicationFormEntity> applicationFormEntities = applicationFormRepository.findByApplicationId(entity.getApplicationId());
|
||||
setAmendmentDetails(entity,response);
|
||||
|
||||
setCriteriaResponses(entity, response, evaluationCriterias);
|
||||
setChecklistResponses(entity, response, checklistEntities);
|
||||
setFieldResponses(entity, response, applicationFormEntities);
|
||||
|
||||
List<EvaluationDocumentRequest> allDocs = prepareEvaluationDocumentBeanList(entity);
|
||||
setEvaluationDocResponse(response, allDocs);
|
||||
setApplicationDetails(response, entity);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private void setAmendmentDetails(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response) {
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequests=applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(entity.getId());
|
||||
List<AmendmentDocumentResponseBean> amendmentDocumentResponseBeans=new ArrayList<>();
|
||||
for(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity:amendmentRequests){
|
||||
AmendmentDocumentResponseBean amendmentDocumentResponseBean=new AmendmentDocumentResponseBean();
|
||||
amendmentDocumentResponseBean.setAmendmentId(applicationAmendmentRequestEntity.getId());
|
||||
String amendmentDocument=applicationAmendmentRequestEntity.getAmendmentDocument();
|
||||
String formField=applicationAmendmentRequestEntity.getFormFields();
|
||||
AmendmentDetailsResponseBean amendmentDetails = Utils.convertStringToObject(amendmentDocument, AmendmentDetailsResponseBean.class);
|
||||
if (amendmentDetails != null) {
|
||||
if (amendmentDetails.getAmendmentDocuments() != null) {
|
||||
List<DocumentResponseBean> documentResponseBeans = Arrays.stream(amendmentDetails.getAmendmentDocuments().split(","))
|
||||
.map(String::trim)
|
||||
.filter(id -> !id.isEmpty())
|
||||
.map(documentId -> applicationAmendmentRequestDao.createDocumentResponseBean(documentId))
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
amendmentDocumentResponseBean.setFileDetail(documentResponseBeans);
|
||||
}
|
||||
amendmentDocumentResponseBean.setFieldId("amend_" + applicationAmendmentRequestEntity.getId());
|
||||
amendmentDocumentResponseBean.setLabel(amendmentDetails.getAmendmentNotes());
|
||||
amendmentDocumentResponseBean.setValid(amendmentDetails.getValid());
|
||||
amendmentDocumentResponseBeans.add(amendmentDocumentResponseBean);
|
||||
}
|
||||
List<AmendmentFormField> amendmentFormFields = Utils.convertJsonStringToList(formField, AmendmentFormField.class);
|
||||
if (amendmentFormFields != null) {
|
||||
for (AmendmentFormField amendmentFormField : amendmentFormFields) {
|
||||
// Skip fields with null or empty fieldValue
|
||||
if (StringUtils.isEmpty(amendmentFormField.getFieldValue())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AmendmentDocumentResponseBean formFieldResponseBean = new AmendmentDocumentResponseBean();
|
||||
formFieldResponseBean.setAmendmentId(applicationAmendmentRequestEntity.getId());
|
||||
formFieldResponseBean.setFieldId(amendmentFormField.getFieldId());
|
||||
formFieldResponseBean.setLabel(amendmentFormField.getLabel());
|
||||
formFieldResponseBean.setValid(amendmentFormField.getValid());
|
||||
|
||||
List<Long> fileIds = applicationAmendmentRequestDao.extractIds(amendmentFormField.getFieldValue());
|
||||
List<DocumentResponseBean> documentResponseBeans = fileIds.stream()
|
||||
.map(fileId -> createDocumentResponseBean(documentService.validateDocument(fileId)))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
formFieldResponseBean.setFileDetail(documentResponseBeans);
|
||||
amendmentDocumentResponseBeans.add(formFieldResponseBean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
response.setAmendmentDetails(amendmentDocumentResponseBeans);
|
||||
}
|
||||
|
||||
private void setEvaluationDocResponse(ApplicationEvaluationResponse response, List<EvaluationDocumentRequest> docRequest) {
|
||||
List<EvaluationDocumentResponse> evaluationDocResponses = new ArrayList<>();
|
||||
|
||||
for (EvaluationDocumentRequest doc : docRequest) {
|
||||
EvaluationDocumentResponse evaluationDocResponse = new EvaluationDocumentResponse();
|
||||
if (doc.getFileValue() != null) {
|
||||
Long fileId = Long.valueOf(doc.getFileValue().toString());
|
||||
documentRepository.findByIdAndNotDeleted(fileId).ifPresent(documentEntity -> {
|
||||
DocumentResponseBean documentResponseBean = new DocumentResponseBean();
|
||||
documentResponseBean.setId(documentEntity.getId());
|
||||
documentResponseBean.setName(documentEntity.getFileName());
|
||||
documentResponseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
|
||||
documentResponseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
|
||||
documentResponseBean.setSourceId(documentEntity.getSourceId());
|
||||
documentResponseBean.setFilePath(documentEntity.getFilePath());
|
||||
documentResponseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
documentResponseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
documentResponseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
evaluationDocResponse.setFileValue(List.of(documentResponseBean));
|
||||
evaluationDocResponse.setNameValue(doc.getNameValue());
|
||||
evaluationDocResponse.setValid(doc.getValid());
|
||||
evaluationDocResponse.setFieldId(doc.getFieldId());
|
||||
});
|
||||
}
|
||||
if (evaluationDocResponse.getFileValue() == null) {
|
||||
continue;
|
||||
}
|
||||
evaluationDocResponses.add(evaluationDocResponse);
|
||||
}
|
||||
response.setEvaluationDocument(evaluationDocResponses);
|
||||
}
|
||||
|
||||
private void populateBasicDetails(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response) {
|
||||
|
||||
response.setId(entity.getId());
|
||||
@@ -156,28 +260,32 @@ public class ApplicationEvaluationDao {
|
||||
private void setCriteriaResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List<EvaluationCriteriaEntity> evaluationCriterias) {
|
||||
|
||||
List<CriteriaResponse> criteriaResponsesFromEntity = entity.getCriteria() != null ?
|
||||
Utils.convertJsonToList(entity.getCriteria(), new TypeReference<List<CriteriaResponse>>() {
|
||||
}) :
|
||||
Utils.convertJsonToList(entity.getCriteria(), new TypeReference<List<CriteriaResponse>>() {}) :
|
||||
new ArrayList<>();
|
||||
|
||||
List<CriteriaResponse> criteriaResponsesFromDB = getCriteriaResponse(entity.getApplicationId());
|
||||
addMissingCriteriaResponses(criteriaResponsesFromEntity, criteriaResponsesFromDB, entity.getApplicationId());
|
||||
criteriaResponsesFromEntity.forEach(criteriaResponse -> {
|
||||
EvaluationCriteriaEntity matchingEvaluationCriteria = evaluationCriterias.stream()
|
||||
.filter(evaluationCriteria -> evaluationCriteria.getId().equals(criteriaResponse.getId())).findFirst().orElse(null);
|
||||
|
||||
if (matchingEvaluationCriteria != null) {
|
||||
criteriaResponse.setLabel(matchingEvaluationCriteria.getLookupData().getValue());
|
||||
criteriaResponse.setMaxScore(matchingEvaluationCriteria.getScore());
|
||||
|
||||
List<CriteriaMappedField> mappedFields = getMappedFieldsForCriteria(matchingEvaluationCriteria.getId(), entity.getApplicationId());
|
||||
criteriaResponse.setCriteriaMappedFields(mappedFields);
|
||||
}
|
||||
});
|
||||
criteriaResponsesFromEntity = criteriaResponsesFromEntity.stream()
|
||||
.filter(criteriaResponse -> {
|
||||
EvaluationCriteriaEntity matchingEvaluationCriteria = evaluationCriterias.stream()
|
||||
.filter(evaluationCriteria -> evaluationCriteria.getId().equals(criteriaResponse.getId())) // Find matching criteria by ID
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (matchingEvaluationCriteria != null) {
|
||||
criteriaResponse.setLabel(matchingEvaluationCriteria.getLookupData().getValue());
|
||||
criteriaResponse.setMaxScore(matchingEvaluationCriteria.getScore());
|
||||
List<CriteriaMappedField> mappedFields = getMappedFieldsForCriteria(matchingEvaluationCriteria.getId(), entity.getApplicationId());
|
||||
criteriaResponse.setCriteriaMappedFields(mappedFields);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
response.setCriteria(criteriaResponsesFromEntity);
|
||||
}
|
||||
|
||||
|
||||
private void addMissingCriteriaResponses(List<CriteriaResponse> criteriaResponsesFromEntity, List<CriteriaResponse> criteriaResponsesFromDB, Long applicationId) {
|
||||
|
||||
Set<Long> existingCriteriaIds = criteriaResponsesFromEntity.stream().map(CriteriaResponse::getId).collect(Collectors.toSet());
|
||||
@@ -282,6 +390,7 @@ public class ApplicationEvaluationDao {
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
documentResponseBeans.add(responseBean);
|
||||
});
|
||||
}
|
||||
@@ -299,27 +408,30 @@ public class ApplicationEvaluationDao {
|
||||
|
||||
|
||||
private void setChecklistResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List<CallTargetAudienceChecklistEntity> checklistEntities) {
|
||||
|
||||
List<ChecklistResponse> checklistResponsesFromEntity = entity.getChecklist() != null ?
|
||||
Utils.convertJsonToList(entity.getChecklist(), new TypeReference<List<ChecklistResponse>>() {
|
||||
}) :
|
||||
Utils.convertJsonToList(entity.getChecklist(), new TypeReference<List<ChecklistResponse>>() {}) :
|
||||
new ArrayList<>();
|
||||
|
||||
List<ChecklistResponse> checklistResponsesFromDB = getChecklistResponse(entity.getApplicationId());
|
||||
addMissingChecklistResponses(checklistResponsesFromEntity, checklistResponsesFromDB);
|
||||
|
||||
checklistResponsesFromEntity.forEach(checklistResponse -> {
|
||||
CallTargetAudienceChecklistEntity matchingChecklist = checklistEntities.stream().filter(checklistEntity -> checklistEntity.getId().equals(checklistResponse.getId()))
|
||||
.findFirst().orElse(null);
|
||||
|
||||
if (matchingChecklist != null) {
|
||||
checklistResponse.setLabel(matchingChecklist.getLookupData().getValue());
|
||||
}
|
||||
});
|
||||
checklistResponsesFromEntity = checklistResponsesFromEntity.stream()
|
||||
.filter(checklistResponse -> {
|
||||
CallTargetAudienceChecklistEntity matchingChecklist = checklistEntities.stream()
|
||||
.filter(checklistEntity -> checklistEntity.getId().equals(checklistResponse.getId())) // Find matching checklist by ID
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (matchingChecklist != null) {
|
||||
checklistResponse.setLabel(matchingChecklist.getLookupData().getValue());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
response.setChecklist(checklistResponsesFromEntity);
|
||||
}
|
||||
|
||||
|
||||
private void addMissingChecklistResponses(List<ChecklistResponse> checklistResponsesFromEntity, List<ChecklistResponse> checklistResponsesFromDB) {
|
||||
|
||||
Set<Long> existingChecklistIds = checklistResponsesFromEntity.stream().map(ChecklistResponse::getId).collect(Collectors.toSet());
|
||||
@@ -333,26 +445,31 @@ public class ApplicationEvaluationDao {
|
||||
|
||||
private void setFieldResponses(ApplicationEvaluationEntity entity, ApplicationEvaluationResponse response, List<ApplicationFormEntity> applicationFormEntities) {
|
||||
|
||||
List<FieldResponse> fieldResponsesFromEntity = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference<List<FieldResponse>>() {
|
||||
}) : new ArrayList<>();
|
||||
List<FieldResponse> fieldResponsesFromEntity = entity.getFile() != null ? Utils.convertJsonToList(entity.getFile(), new TypeReference<List<FieldResponse>>() {}) : new ArrayList<>();
|
||||
List<FieldResponse> fieldResponsesFromDB = getFieldResponses(entity.getApplicationId());
|
||||
addMissingFieldResponses(fieldResponsesFromEntity, fieldResponsesFromDB);
|
||||
|
||||
Set<String> processedFieldIds = new HashSet<>();
|
||||
List<FieldResponse> validFieldResponses = new ArrayList<>();
|
||||
|
||||
fieldResponsesFromEntity.forEach(fieldResponse -> {
|
||||
if (processedFieldIds.contains(fieldResponse.getId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Boolean[] allDocumentsDeleted = {true};
|
||||
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
|
||||
|
||||
applicationFormEntities.forEach(applicationForm -> {
|
||||
FormEntity formEntity = applicationForm.getForm();
|
||||
if (formEntity != null) {
|
||||
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class);
|
||||
// Convert the form to a list of content response beans
|
||||
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
|
||||
contentResponseBeans.forEach(contentResponseBean -> {
|
||||
// Check if this is a file upload field that matches the current field response
|
||||
if ("fileupload".equals(contentResponseBean.getName()) && contentResponseBean.getId().equals(fieldResponse.getId())) {
|
||||
String label = null;
|
||||
// Set the label if available
|
||||
if (contentResponseBean.getSettings() != null) {
|
||||
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
|
||||
if ("label".equals(setting.getName())) {
|
||||
@@ -371,36 +488,44 @@ public class ApplicationEvaluationDao {
|
||||
ApplicationFormFieldEntity formField = optionalFormField.get();
|
||||
if (formField.getFieldValue() != null) {
|
||||
String[] documentIds = formField.getFieldValue().split(",");
|
||||
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
|
||||
|
||||
for (String docId : documentIds) {
|
||||
if (Boolean.FALSE.equals(docId.isEmpty())){
|
||||
if (!docId.trim().isEmpty()) {
|
||||
Long documentId = Long.valueOf(docId.trim());
|
||||
|
||||
documentRepository.findByIdAndNotDeleted(documentId).ifPresent(documentEntity -> {
|
||||
DocumentResponseBean responseBean = new DocumentResponseBean();
|
||||
responseBean.setId(documentEntity.getId());
|
||||
responseBean.setName(documentEntity.getFileName());
|
||||
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
|
||||
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
|
||||
responseBean.setSourceId(documentEntity.getSourceId());
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
documentResponseBeans.add(responseBean);
|
||||
if (documentEntity != null && !documentEntity.getIsDeleted()) {
|
||||
DocumentResponseBean responseBean = new DocumentResponseBean();
|
||||
responseBean.setId(documentEntity.getId());
|
||||
responseBean.setName(documentEntity.getFileName());
|
||||
responseBean.setType(DocumentTypeEnum.valueOf(documentEntity.getType()));
|
||||
responseBean.setSource(DocumentSourceTypeEnum.valueOf(documentEntity.getSource()));
|
||||
responseBean.setSourceId(documentEntity.getSourceId());
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
documentResponseBeans.add(responseBean);
|
||||
allDocumentsDeleted[0] = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fieldResponse.setFileDetail(documentResponseBeans);
|
||||
}
|
||||
}
|
||||
processedFieldIds.add(fieldResponse.getId());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (Boolean.FALSE.equals(allDocumentsDeleted[0]) && Boolean.FALSE.equals(documentResponseBeans.isEmpty())) {
|
||||
fieldResponse.setFileDetail(documentResponseBeans);
|
||||
validFieldResponses.add(fieldResponse);
|
||||
}
|
||||
|
||||
processedFieldIds.add(fieldResponse.getId());
|
||||
});
|
||||
response.setFiles(fieldResponsesFromEntity);
|
||||
response.setFiles(validFieldResponses);
|
||||
}
|
||||
|
||||
private void addMissingFieldResponses(List<FieldResponse> fieldResponsesFromEntity, List<FieldResponse> fieldResponsesFromDB) {
|
||||
@@ -417,21 +542,44 @@ public class ApplicationEvaluationDao {
|
||||
private void setApplicationDetails(ApplicationEvaluationResponse response, ApplicationEvaluationEntity entity) {
|
||||
|
||||
ApplicationEntity application = applicationService.validateApplication(entity.getApplicationId() != null ? entity.getApplicationId() : null);
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository
|
||||
.findByApplicationIdAndIsDeletedFalse(entity.getApplicationId()).orElse(null);
|
||||
|
||||
UserEntity user = userService.validateUser(application.getUserId());
|
||||
|
||||
CallEntity call = callRepository.findCallEntityByApplicationId(entity.getApplicationId());
|
||||
|
||||
String firstName = user.getFirstName() != null ? user.getFirstName() : "";
|
||||
String lastName = user.getLastName() != null ? user.getLastName() : "";
|
||||
String firstName = user.getBeneficiary().getFirstName() != null ? user.getBeneficiary().getFirstName() : "";
|
||||
String lastName = user.getBeneficiary().getLastName() != null ? user.getBeneficiary().getLastName() : "";
|
||||
String beneficiary = String.join(" ", firstName, lastName).trim();
|
||||
response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(application.getStatus()));
|
||||
response.setBeneficiary(beneficiary);
|
||||
response.setNdg(application.getNdg() != null ? application.getNdg() : null);
|
||||
response.setAppointmentId(application.getAppointmentId() != null ? application.getAppointmentId() : null);
|
||||
response.setSubmissionDate(application.getSubmissionDate());
|
||||
response.setMinScore(call.getThreshold() != null ? call.getThreshold() : null);
|
||||
response.setCallName(application.getCall().getName() != null ? application.getCall().getName() : null);
|
||||
response.setProtocolNumber((application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null) ? application.getProtocol().getProtocolNumber() : null);
|
||||
response.setSubmissionDate(application.getSubmissionDate() != null ? application.getSubmissionDate() : null);
|
||||
if (assignedApplications != null) {
|
||||
response.setAssignedAt(assignedApplications.getAssignedAt());
|
||||
}
|
||||
response.setEvaluationEndDate(entity.getEndDate());
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(application.getId());
|
||||
if(assignedApplicationsOptional.isPresent()){
|
||||
response.setAssignedUserId(assignedApplicationsOptional.get().getUserId());
|
||||
UserEntity assignedUser = userService.validateUser(assignedApplicationsOptional.get().getUserId());
|
||||
String assignedUserFirstName = assignedUser.getFirstName() != null ? assignedUser.getFirstName() : "";
|
||||
String assignedUserLastName = assignedUser.getLastName() != null ? assignedUser.getLastName() : "";
|
||||
String userName = String.join(" ", assignedUserFirstName, assignedUserLastName).trim();
|
||||
response.setAssignedUserName(userName);
|
||||
}
|
||||
LocalDateTime callEndDate = application.getCall().getEndDate();
|
||||
response.setCallEndDate(callEndDate);
|
||||
if (application.getCompanyId() != null) {
|
||||
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
|
||||
response.setCompanyName(company.getCompanyName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -446,22 +594,47 @@ public class ApplicationEvaluationDao {
|
||||
Optional<AssignedApplicationsEntity> assignedApplications =
|
||||
assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId);
|
||||
ApplicationEvaluationEntity oldApplicationEvaluation = null;
|
||||
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
|
||||
VersionActionTypeEnum actionType;
|
||||
if (existingEntityOptional.isPresent()) {
|
||||
entity = existingEntityOptional.get();
|
||||
oldApplicationEvaluation = Utils.getClonedEntityForData(entity);
|
||||
entity.setCriteria(Utils.convertObjectToJson(filterNonNullCriteria(processCriteria(entity, req))));
|
||||
entity.setChecklist(Utils.convertObjectToJson(filterNonNullChecklist(processChecklist(entity, req))));
|
||||
entity.setFile(Utils.convertObjectToJson(filterNonNullFields(processField(entity, req))));
|
||||
if(req.getCriteria()!=null) {
|
||||
entity.setCriteria(Utils.convertObjectToJson(processCriteria(entity, req)));
|
||||
}
|
||||
if(req.getChecklist()!=null) {
|
||||
entity.setChecklist(Utils.convertObjectToJson(processChecklist(entity, req)));
|
||||
}
|
||||
if(req.getFiles()!=null) {
|
||||
entity.setFile(Utils.convertObjectToJson(processField(entity, req)));
|
||||
}
|
||||
entity.setIsDeleted(false);
|
||||
setIfUpdated(entity::getNote, entity::setNote, req.getNote());
|
||||
setIfUpdated(entity::getMotivation, entity::setMotivation, req.getMotivation());
|
||||
actionType = VersionActionTypeEnum.UPDATE;
|
||||
} else {
|
||||
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsService.validateAssignedApplication(assignedApplicationId);
|
||||
ApplicationEntity application = applicationService.validateApplication(assignedApplicationsEntity.getApplication().getId());
|
||||
entity = convertToEntity(user, req, assignedApplicationId);
|
||||
actionType = VersionActionTypeEnum.INSERT;
|
||||
|
||||
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_CREATION);
|
||||
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_CREATION);
|
||||
notificationDao.sendNotificationToInstructor(placeHolders,entity,NotificationTypeEnum.EVALUATION_CREATION);
|
||||
|
||||
}
|
||||
ApplicationStatusForEvaluation status = req.getApplicationStatus();
|
||||
// Fetch all amendment request entities associated with the evaluation ID
|
||||
List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities =
|
||||
applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(entity.getId());
|
||||
if(req.getEvaluationDocument()!=null) {
|
||||
updateApplicationEvaluation(assignedApplicationId, req.getEvaluationDocument());
|
||||
}
|
||||
// Fetch amendment details from the request
|
||||
if(req.getAmendmentDetails()!=null) {
|
||||
List<AmendmentDetailsRequest> amendmentDetailsRequests = req.getAmendmentDetails();
|
||||
|
||||
updateAmendmentDocumentsAndFormFields(applicationAmendmentRequestEntities, amendmentDetailsRequests);
|
||||
}
|
||||
|
||||
ApplicationEvaluationEntity savedEntity = applicationEvaluationRepository.save(entity);
|
||||
|
||||
@@ -477,22 +650,212 @@ public class ApplicationEvaluationDao {
|
||||
}
|
||||
}
|
||||
|
||||
private void updateAmendmentDocumentsAndFormFields(List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities, List<AmendmentDetailsRequest> amendmentFormFields) {
|
||||
// Iterate through amendment request entities
|
||||
|
||||
private List<ChecklistRequest> filterNonNullChecklist(List<ChecklistRequest> checklistRequests) {
|
||||
//
|
||||
Map<Long,List<AmendmentDetailsRequest>> amendmentFormFieldsMap = amendmentFormFields.stream().collect(Collectors.groupingBy(AmendmentDetailsRequest::getAmendmentId,HashMap::new,Collectors.toCollection(ArrayList::new)));
|
||||
// amendmentFormFields.forEach(data->{
|
||||
// ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestMap.get(data.getAmendmentId());
|
||||
// if (data.getFieldId().contains("amend_")){
|
||||
// updateAmendmentDocument(applicationAmendmentRequestEntity, data);
|
||||
// }
|
||||
// });
|
||||
applicationAmendmentRequestEntities.forEach(applicationAmendmentRequestEntity->{
|
||||
ApplicationAmendmentRequestEntity oldEntity = Utils.getClonedEntityForData(applicationAmendmentRequestEntity);
|
||||
updateAmendment(applicationAmendmentRequestEntity, amendmentFormFieldsMap.get(applicationAmendmentRequestEntity.getId()));
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().actionType(VersionActionTypeEnum.UPDATE).oldData(oldEntity).newData(applicationAmendmentRequestEntity).build());
|
||||
});
|
||||
applicationAmendmentRequestRepository.saveAll(applicationAmendmentRequestEntities);
|
||||
|
||||
return checklistRequests.stream().filter(request -> request.getValid() != null).collect(Collectors.toList());
|
||||
|
||||
// for (ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity : applicationAmendmentRequestEntities) {
|
||||
// // Process form fields if present
|
||||
// if (applicationAmendmentRequestEntity.getFormFields() != null) {
|
||||
// // Parse existing form fields from JSON
|
||||
// List<AmendmentFormFieldRequest> existingFormFields =
|
||||
// Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getFormFields(), AmendmentFormFieldRequest.class);
|
||||
//
|
||||
// // Prepare a new list to hold updated form fields
|
||||
// List<AmendmentFormFieldRequest> updatedFormFields = new ArrayList<>();
|
||||
//
|
||||
// // Map amendment details for quick lookup by amendment ID
|
||||
// Map<Long, Object> amendmentDetailsMap = amendmentFormFields.stream()
|
||||
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
|
||||
// .filter(details -> details.getFieldValue() != null) // Null check for getFormFieldDocuments
|
||||
// .collect(Collectors.toMap(
|
||||
// AmendmentDetailsRequest::getAmendmentId,
|
||||
// AmendmentDetailsRequest::getFieldValue
|
||||
// ));
|
||||
// // Get corresponding amendment documents for the current entity
|
||||
// List<AmendmentFormFieldRequest> amendmentDocuments = (List<AmendmentFormFieldRequest>) amendmentDetailsMap.get(applicationAmendmentRequestEntity.getId());
|
||||
// if (amendmentDocuments != null) {
|
||||
// // Update existing form fields with new values
|
||||
// for (AmendmentFormFieldRequest existingField : existingFormFields) {
|
||||
// for (AmendmentFormFieldRequest newField : amendmentDocuments) {
|
||||
// if (existingField.getFieldId().equals(newField.getFieldId())) {
|
||||
// // Update fields if there are changes
|
||||
// Utils.setIfUpdated(existingField::getValid, existingField::setValid, newField.getValid());
|
||||
// Utils.setIfUpdated(existingField::getFieldValue, existingField::setFieldValue, newField.getFieldValue());
|
||||
//
|
||||
// updatedFormFields.add(existingField);
|
||||
// break; // Move to the next existing field
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Convert updated form fields back to JSON and save to the database
|
||||
// applicationAmendmentRequestEntity.setFormFields(Utils.convertListToJsonString(updatedFormFields));
|
||||
// applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Process amendment documents if present
|
||||
// if (applicationAmendmentRequestEntity.getAmendmentDocument() != null) {
|
||||
// String existingDocumentIds = applicationAmendmentRequestEntity.getAmendmentDocument();
|
||||
//
|
||||
// // Split comma-separated document IDs into a list
|
||||
// List<String> existingDocumentIdList = Arrays.stream(existingDocumentIds.split(","))
|
||||
// .map(String::trim)
|
||||
// .filter(id -> !id.isEmpty())
|
||||
// .collect(Collectors.toList());
|
||||
//
|
||||
// List<String> updatedDocumentIdList = new ArrayList<>();
|
||||
// Map<Long, Object> amendmentDetailsMap = amendmentFormFields.stream()
|
||||
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
|
||||
// .collect(Collectors.toMap(
|
||||
// AmendmentDetailsRequest::getAmendmentId,
|
||||
// AmendmentDetailsRequest::getFieldValue
|
||||
// ));
|
||||
//
|
||||
// String amendmentDocumentIds = (String) amendmentDetailsMap.get(applicationAmendmentRequestEntity.getId());
|
||||
// if (amendmentDocumentIds != null) {
|
||||
// // Split and validate new document IDs
|
||||
// List<String> newDocumentIdList = Arrays.stream(amendmentDocumentIds.split(","))
|
||||
// .map(String::trim)
|
||||
// .filter(id -> !id.isEmpty())
|
||||
// .collect(Collectors.toList());
|
||||
//
|
||||
// for (String existingId : existingDocumentIdList) {
|
||||
// for (String newId : newDocumentIdList) {
|
||||
// if (existingId.equals(newId)) {
|
||||
// Optional<DocumentEntity> documentEntity = documentRepository.findByIdAndNotDeleted(Long.valueOf(newId));
|
||||
// if(documentEntity.isPresent()) {
|
||||
// updatedDocumentIdList.add(newId);
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Add any new IDs not in the existing list
|
||||
// for (String newId : newDocumentIdList) {
|
||||
// if (!existingDocumentIdList.contains(newId)) {
|
||||
// Optional<DocumentEntity> documentEntity = documentRepository.findByIdAndNotDeleted(Long.valueOf(newId));
|
||||
// if(documentEntity.isPresent()) {
|
||||
// updatedDocumentIdList.add(newId);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// String updatedDocumentIds = String.join(",", updatedDocumentIdList);
|
||||
//
|
||||
// // Create the AmendmentDetailsResponseBean for structured data
|
||||
// AmendmentDetailsResponseBean amendmentDetails = new AmendmentDetailsResponseBean();
|
||||
// amendmentDetails.setAmendmentDocuments(updatedDocumentIds);
|
||||
// AmendmentDetailsRequest amendmentDetailsRequest = amendmentFormFields.stream()
|
||||
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
|
||||
// .findFirst()
|
||||
// .orElse(null);
|
||||
//
|
||||
// if (amendmentDetailsRequest != null) {
|
||||
// amendmentDetails.setValid(amendmentDetailsRequest.getValid());
|
||||
// } else {
|
||||
// amendmentDetails.setValid(false);
|
||||
// }
|
||||
// String amendmentDetailsJson = Utils.convertListToJsonString(Collections.singletonList(amendmentDetails));
|
||||
// applicationAmendmentRequestEntity.setAmendmentDocument(amendmentDetailsJson);
|
||||
// applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
private List<CriteriaRequest> filterNonNullCriteria(List<CriteriaRequest> criteriaRequests) {
|
||||
private void updateAmendment(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity, List<AmendmentDetailsRequest> amendmentDetailsRequestList) {
|
||||
if (CollectionUtils.isEmpty(amendmentDetailsRequestList)) {
|
||||
return;
|
||||
}
|
||||
Map<String, AmendmentFormField> formFieldsMap = null;
|
||||
List<AmendmentFormField> formFieldList = Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getFormFields(), AmendmentFormField.class);
|
||||
if(Boolean.FALSE.equals(CollectionUtils.isEmpty(formFieldList))){
|
||||
formFieldsMap = formFieldList.stream().collect(Collectors.toMap(AmendmentFormField::getFieldId, Function.identity()));
|
||||
}
|
||||
updateAmendmentData(applicationAmendmentRequestEntity, amendmentDetailsRequestList, formFieldsMap);
|
||||
|
||||
return criteriaRequests.stream().filter(request -> request.getScore() != null && request.getValid() != null).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<FieldRequest> filterNonNullFields(List<FieldRequest> fieldRequests) {
|
||||
|
||||
return fieldRequests.stream().filter(request -> request.getValid() != null).collect(Collectors.toList());
|
||||
private static void updateAmendmentData(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity, List<AmendmentDetailsRequest> amendmentDetailsRequestList, Map<String, AmendmentFormField> formFieldsMap) {
|
||||
amendmentDetailsRequestList.forEach(amendmentDetailsRequest -> {
|
||||
if (amendmentDetailsRequest.getFieldId().contains("amend_")) {
|
||||
AmendmentDetailsResponseBean amendmentDetails = Utils.convertStringToObject(applicationAmendmentRequestEntity.getAmendmentDocument(), AmendmentDetailsResponseBean.class);
|
||||
if(amendmentDetails!=null) {
|
||||
amendmentDetails.setValid(amendmentDetailsRequest.getValid());
|
||||
applicationAmendmentRequestEntity.setAmendmentDocument(Utils.convertObjectToString(amendmentDetails));
|
||||
}
|
||||
} else if(Boolean.FALSE.equals(CollectionUtils.isEmpty(formFieldsMap))){
|
||||
AmendmentFormField amendmentFormField = formFieldsMap.get(amendmentDetailsRequest.getFieldId());
|
||||
amendmentFormField.setValid(amendmentDetailsRequest.getValid());
|
||||
}
|
||||
});
|
||||
applicationAmendmentRequestEntity.setFormFields(Utils.convertListToJsonString(formFieldsMap.values().stream().toList()));
|
||||
}
|
||||
|
||||
|
||||
// private void updateAmendmentDocuments(List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities, List<AmendmentDetailsRequest> amendmentFormFields) {
|
||||
// for (ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity : applicationAmendmentRequestEntities) {
|
||||
// // Skip if there are no amendment documents
|
||||
// if (applicationAmendmentRequestEntity.getAmendmentDocument() == null) {
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// // Parse existing amendment fields from JSON
|
||||
// List<AmendmentFieldRequest> existingAmendmentFields =
|
||||
// Utils.convertJsonStringToList(applicationAmendmentRequestEntity.getAmendmentDocument(), AmendmentFieldRequest.class);
|
||||
//
|
||||
// // Prepare a new list to hold updated amendment fields
|
||||
// List<AmendmentFieldRequest> updatedAmendmentFields = new ArrayList<>();
|
||||
//
|
||||
// // Map amendment details for quick lookup by amendment ID
|
||||
// Map<Long, List<AmendmentFieldRequest>> amendmentDetailsMap = amendmentFormFields.stream()
|
||||
// .filter(details -> applicationAmendmentRequestEntity.getId().equals(details.getAmendmentId()))
|
||||
// .collect(Collectors.toMap(AmendmentDetailsRequest::getAmendmentId, AmendmentDetailsRequest::getAmendmentDocuments));
|
||||
//
|
||||
// // Get corresponding amendment documents for the current entity
|
||||
// List<AmendmentFieldRequest> amendmentDocuments = amendmentDetailsMap.get(applicationAmendmentRequestEntity.getId());
|
||||
// if (amendmentDocuments == null) {
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// // Update existing amendment fields with new values
|
||||
// for (AmendmentFieldRequest existingField : existingAmendmentFields) {
|
||||
// for (AmendmentFieldRequest newField : amendmentDocuments) {
|
||||
// if (existingField.getFieldId().equals(newField.getFieldId())) {
|
||||
// // Update fields if there are changes
|
||||
// Utils.setIfUpdated(existingField::getIsValid, existingField::setIsValid, newField.getIsValid());
|
||||
// Utils.setIfUpdated(existingField::getFileValue, existingField::setFileValue, newField.getFileValue());
|
||||
// Utils.setIfUpdated(existingField::getNameValue, existingField::setNameValue, newField.getNameValue());
|
||||
//
|
||||
// updatedAmendmentFields.add(existingField);
|
||||
// break; // Move to the next existing field
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Convert updated fields back to JSON and save to the database
|
||||
// applicationAmendmentRequestEntity.setAmendmentDocument(Utils.convertListToJsonString(updatedAmendmentFields));
|
||||
// applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
|
||||
// }
|
||||
// }
|
||||
|
||||
private List<CriteriaRequest> processCriteria(ApplicationEvaluationEntity entity, ApplicationEvaluationRequest req) {
|
||||
|
||||
List<CriteriaRequest> incomingCriteriaList = Optional.ofNullable(req.getCriteria()).orElse(new ArrayList<>());
|
||||
@@ -612,11 +975,52 @@ public class ApplicationEvaluationDao {
|
||||
return entityOptional.get();
|
||||
}
|
||||
|
||||
public void validatePreinstructor(HttpServletRequest request,Long applicationId,Long assignedApplicationId){
|
||||
if (applicationId == null && assignedApplicationId == null) {
|
||||
throw new CustomValidationException(
|
||||
Status.BAD_REQUEST,
|
||||
Translator.toLocale(GepafinConstant.EITHER_APPLICATION_OR_ASSIGNED_APPLICATION_ID_REQUIRED_MSG)
|
||||
);
|
||||
}
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByApplicationIdOrIdAndIsDeletedFalse(applicationId,assignedApplicationId);
|
||||
|
||||
public ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(UserEntity user, Long applicationId, Long assignedApplicationId) {
|
||||
if (assignedApplicationId != null) {
|
||||
assignedApplicationsOptional = assignedApplicationsOptional.filter(a -> a.getId().equals(assignedApplicationId));
|
||||
}
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsOptional
|
||||
.orElseThrow(() -> new CustomValidationException(
|
||||
Status.BAD_REQUEST,
|
||||
Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_WITH_ID_MSG)
|
||||
));
|
||||
if (applicationId == null) {
|
||||
applicationId = assignedApplications.getApplication().getId();
|
||||
}
|
||||
validator.validatePreInstructor(request, assignedApplications.getUserId());
|
||||
}
|
||||
public ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(HttpServletRequest request, UserEntity user, Long applicationID, Long assignedApplicationID) {
|
||||
Long applicationId;
|
||||
Long assignedApplicationId;
|
||||
validatePreinstructor(request, applicationID, assignedApplicationID);
|
||||
|
||||
if (applicationID == null && assignedApplicationID != null) {
|
||||
assignedApplicationId = assignedApplicationID;
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId);
|
||||
|
||||
applicationId = assignedApplicationsOptional.map(a -> a.getApplication().getId()).orElse(null);
|
||||
} else {
|
||||
applicationId = applicationID;
|
||||
if (assignedApplicationID == null && applicationID != null) {
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
|
||||
|
||||
assignedApplicationId = assignedApplicationsOptional.map(AssignedApplicationsEntity::getId).orElse(null);
|
||||
} else {
|
||||
assignedApplicationId = assignedApplicationID;
|
||||
}
|
||||
}
|
||||
applicationService.validateApplication(applicationId);
|
||||
|
||||
Optional<ApplicationEvaluationEntity> entityOptional;
|
||||
|
||||
if (applicationId != null && assignedApplicationId != null) {
|
||||
@@ -628,11 +1032,19 @@ public class ApplicationEvaluationDao {
|
||||
} else {
|
||||
entityOptional = applicationEvaluationRepository.findFirstByIsDeletedFalseOrderByCreatedDateDesc();
|
||||
}
|
||||
return entityOptional.map(this::convertToResponse)
|
||||
return entityOptional.map(this::convertToResponse)
|
||||
.orElseGet(() -> {
|
||||
return getEvaluationResponseByApplicationid(user, applicationId, assignedApplicationId);
|
||||
});
|
||||
}
|
||||
private List<EvaluationDocumentRequest> prepareEvaluationDocumentBeanList(ApplicationEvaluationEntity entity) {
|
||||
List<EvaluationDocumentRequest> docRequest = new ArrayList<>();
|
||||
|
||||
if (entity != null && entity.getEvaluationDocument() != null) {
|
||||
docRequest = Utils.convertJsonToList(entity.getEvaluationDocument(), new TypeReference<List<EvaluationDocumentRequest>>() {});
|
||||
}
|
||||
return docRequest;
|
||||
}
|
||||
|
||||
public ApplicationEvaluationResponse getEvaluationResponseByApplicationid(UserEntity user, Long applicationId, Long assignedApplicationId) {
|
||||
|
||||
@@ -730,7 +1142,7 @@ public class ApplicationEvaluationDao {
|
||||
if (!mappedFieldMap.containsKey(formFieldId)) {
|
||||
// CriteriaMappedField mappedField = new CriteriaMappedField();
|
||||
CriteriaMappedField mappedField = populateMappedField(formFieldId, criteriaFormField, applicationForm, applicationId);
|
||||
if(mappedField != null) {
|
||||
if(mappedField != null) {
|
||||
mappedFieldMap.put(formFieldId, mappedField);
|
||||
}
|
||||
}
|
||||
@@ -859,7 +1271,7 @@ public class ApplicationEvaluationDao {
|
||||
}
|
||||
|
||||
|
||||
private DocumentResponseBean createDocumentResponseBean(DocumentEntity documentEntity) {
|
||||
public DocumentResponseBean createDocumentResponseBean(DocumentEntity documentEntity) {
|
||||
DocumentResponseBean responseBean = new DocumentResponseBean();
|
||||
responseBean.setId(documentEntity.getId());
|
||||
responseBean.setName(documentEntity.getFileName());
|
||||
@@ -869,6 +1281,7 @@ public class ApplicationEvaluationDao {
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
return responseBean;
|
||||
}
|
||||
|
||||
@@ -941,6 +1354,7 @@ public class ApplicationEvaluationDao {
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
documentResponseBeans.add(responseBean);
|
||||
});
|
||||
}
|
||||
@@ -961,16 +1375,27 @@ public class ApplicationEvaluationDao {
|
||||
private void setApplicationDetails(ApplicationEvaluationResponse response, Long applicationId, UserEntity user) {
|
||||
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository
|
||||
.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
|
||||
userService.validateUser(application.getUserId());
|
||||
String firstName = user.getFirstName() != null ? user.getFirstName() : "";
|
||||
String lastName = user.getLastName() != null ? user.getLastName() : "";
|
||||
|
||||
String firstName = user.getBeneficiary().getFirstName() != null ? user.getBeneficiary().getFirstName() : "";
|
||||
String lastName = user.getBeneficiary().getLastName() != null ? user.getBeneficiary().getLastName() : "";
|
||||
|
||||
String beneficiary = String.join(" ", firstName, lastName).trim();
|
||||
response.setBeneficiary(beneficiary);
|
||||
|
||||
response.setSubmissionDate(application.getSubmissionDate());
|
||||
response.setNdg(application.getNdg() != null ? application.getNdg() : null);
|
||||
response.setAppointmentId(application.getAppointmentId() != null ? application.getAppointmentId() : null);
|
||||
response.setCallName(application.getCall().getName() != null ? application.getCall().getName() : null);
|
||||
response.setProtocolNumber((application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null) ? application.getProtocol().getProtocolNumber() : null);
|
||||
response.setSubmissionDate(application.getSubmissionDate() != null ? application.getSubmissionDate() : null);
|
||||
if (assignedApplications != null) {
|
||||
response.setAssignedAt(assignedApplications.getAssignedAt());
|
||||
}
|
||||
if (application.getCompanyId() != null) {
|
||||
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
|
||||
response.setCompanyName(company.getCompanyName());
|
||||
}
|
||||
|
||||
}
|
||||
private Optional<ApplicationFormFieldEntity> findFormFieldValue(Long applicationId, String formFieldId) {
|
||||
@@ -1180,6 +1605,7 @@ public class ApplicationEvaluationDao {
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
return responseBean;
|
||||
}
|
||||
|
||||
@@ -1306,6 +1732,7 @@ public class ApplicationEvaluationDao {
|
||||
responseBean.setFilePath(documentEntity.getFilePath());
|
||||
responseBean.setCreatedDate(documentEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(documentEntity.getUpdatedDate());
|
||||
responseBean.setDocumentAttachmentId(documentEntity.getDocumentAttachmentId());
|
||||
documentResponseBeans.add(responseBean);
|
||||
});
|
||||
}
|
||||
@@ -1363,9 +1790,14 @@ public class ApplicationEvaluationDao {
|
||||
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(existingEntity);
|
||||
AssignedApplicationsEntity oldAssignedApplication = Utils.getClonedEntityForData(assignedApplicationsEntity);
|
||||
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequest = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(existingEntity.getId(),List.of(ApplicationAmendmentRequestEnum.AWAITING.getValue(),ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue()));
|
||||
if(amendmentRequest !=null && Boolean.FALSE.equals(amendmentRequest.isEmpty())){
|
||||
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_CANNOT_APPROVED_OR_REJECTED));
|
||||
}
|
||||
String statusType = application.getStatus();
|
||||
if (application.getStatus().equals(ApplicationStatusTypeEnum.APPROVED.getValue()) || application.getStatus().equals(ApplicationStatusTypeEnum.REJECTED.getValue())) {
|
||||
existingEntity.setStatus(ApplicationEvaluationStatusTypeEnum.CLOSE.getValue());
|
||||
existingEntity.setClosingDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CLOSE.getValue());
|
||||
}
|
||||
entity = applicationEvaluationRepository.save(existingEntity);
|
||||
@@ -1381,20 +1813,55 @@ public class ApplicationEvaluationDao {
|
||||
}
|
||||
|
||||
|
||||
List<ApplicationAmendmentRequestEntity> amendmentRequest = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(existingEntity.getId(),ApplicationAmendmentRequestEnum.AWAITING.getValue());
|
||||
if(amendmentRequest !=null && Boolean.FALSE.equals(amendmentRequest.isEmpty())){
|
||||
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_CANNOT_APPROVED_OR_REJECTED));
|
||||
}
|
||||
|
||||
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.APPROVED.getValue())))) {
|
||||
emailNotificationDao.sendAdmissibilityNotificationEmailForApprovedApplication(application);
|
||||
}
|
||||
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.REJECTED.getValue())))) {
|
||||
emailNotificationDao.sendInadmissibilityEmailForRejectedApplication(application,existingEntity);
|
||||
}
|
||||
|
||||
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_RESULT);
|
||||
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_RESULT);
|
||||
notificationDao.sendNotificationToInstructor(placeHolders,existingEntity,NotificationTypeEnum.EVALUATION_RESULT);
|
||||
|
||||
return convertToResponse(entity);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ApplicationEvaluationEntity validateApplicationEvaluationByApplicationId(Long applicationId) {
|
||||
return applicationEvaluationRepository
|
||||
.findByApplicationIdAndIsDeletedFalse(applicationId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.APPLICATION_EVALUATION_NOT_FOUND)));
|
||||
}
|
||||
|
||||
public ApplicationEvaluationResponse updateApplicationEvaluation(
|
||||
Long assignedApplicationId,
|
||||
List<EvaluationDocumentRequest> docRequest) {
|
||||
Optional<ApplicationEvaluationEntity> entityOptional=applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId);
|
||||
ApplicationEvaluationEntity applicationEvaluationEntity =null;
|
||||
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(entityOptional.get());
|
||||
applicationEvaluationEntity = entityOptional.get();
|
||||
|
||||
if (docRequest != null) {
|
||||
List<EvaluationDocumentRequest> existingDocs = new ArrayList<>();
|
||||
|
||||
for (EvaluationDocumentRequest doc : docRequest) {
|
||||
if (doc.getFileValue() != null) {
|
||||
Long fileId = Long.valueOf(doc.getFileValue());
|
||||
documentService.validateDocument(fileId);
|
||||
existingDocs.add(doc);
|
||||
}
|
||||
}
|
||||
String updatedEvaluationDocJson = Utils.convertObjectToJson(existingDocs);
|
||||
applicationEvaluationEntity.setEvaluationDocument(updatedEvaluationDocJson);
|
||||
}
|
||||
ApplicationEvaluationEntity savedEntity = applicationEvaluationRepository.save(applicationEvaluationEntity);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Upload Document in Application Evaluation" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluation).newData(savedEntity).build());
|
||||
return convertToResponse(savedEntity);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,918 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.amazonaws.services.s3.model.GetObjectRequest;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import feign.FeignException;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
|
||||
import net.gepafin.tendermanagement.constants.AppointmentApiConstant;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
import net.gepafin.tendermanagement.entities.DocumentEntity;
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.AppointmentCreationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.AppointmentNdgRequest;
|
||||
import net.gepafin.tendermanagement.model.request.AppointmentVisuraListRequest;
|
||||
import net.gepafin.tendermanagement.model.request.AppointmentVisuraRequest;
|
||||
import net.gepafin.tendermanagement.model.request.CreateAppointmentRequest;
|
||||
import net.gepafin.tendermanagement.model.request.NotificationReq;
|
||||
import net.gepafin.tendermanagement.model.request.UploadDocToExternalSystemRequest;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AppointmentCreationResponse;
|
||||
import net.gepafin.tendermanagement.model.response.AppointmentLoginResponse;
|
||||
import net.gepafin.tendermanagement.model.response.DocumentUploadResponse;
|
||||
import net.gepafin.tendermanagement.model.response.NdgResponse;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.CompanyRepository;
|
||||
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.HubRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import net.gepafin.tendermanagement.service.feignClient.AppointmentApiService;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AppointmentDao {
|
||||
|
||||
@Value("${appointment.portal.user}")
|
||||
private String user;
|
||||
|
||||
@Value("${appointment.portal.password}")
|
||||
private String password;
|
||||
|
||||
@Value("${appointment.portal.source}")
|
||||
private String source;
|
||||
|
||||
@Value("${appointment.portal.context}")
|
||||
private String context;
|
||||
|
||||
@Value("${default.hub.uuid}")
|
||||
private String defaultHubUuid;
|
||||
|
||||
@Value("${aws.s3.url}")
|
||||
private String s3Url;
|
||||
|
||||
@Value("${aws.s3.bucket.name}")
|
||||
private String OLD_BUCKET;
|
||||
|
||||
@Value("${flagDaFirmare}")
|
||||
private Boolean flagDaFirmare;
|
||||
|
||||
@Autowired
|
||||
private HubRepository hubRepository;
|
||||
|
||||
@Autowired
|
||||
private AppointmentApiService appointmentApiService;
|
||||
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
|
||||
@Autowired
|
||||
private ApplicationRepository applicationRepository;
|
||||
|
||||
@Autowired
|
||||
private CompanyRepository companyRepository;
|
||||
|
||||
@Autowired
|
||||
private DocumentDao documentDao;
|
||||
|
||||
@Autowired
|
||||
private AmazonS3Client s3Client;
|
||||
|
||||
@Autowired
|
||||
private DocumentRepository documentRepository;
|
||||
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private LoggingUtil loggingUtil;
|
||||
|
||||
@Autowired
|
||||
private TokenProvider tokenProvider;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
private final Map<Long, ExecutorService> executorMap = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<Long, ExecutorService> threadForDocumentMap = new ConcurrentHashMap<>();
|
||||
|
||||
private static final ThreadLocal<Long> threadLocalHubId = new ThreadLocal<>();
|
||||
|
||||
public NdgResponse checkNdgForAppointment(Long applicationId) {
|
||||
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
NdgResponse ndgResponse = new NdgResponse();
|
||||
if (application.getNdgStatus() != null && application.getNdgStatus().equalsIgnoreCase(GepafinConstant.NDG_IN_PROGRESS)) {
|
||||
throw new CustomValidationException(Status.SUCCESS, Translator.toLocale(GepafinConstant.NDG_GENERATION_IS_IN_PROGRESS));
|
||||
}
|
||||
|
||||
if (application.getNdgStatus() != null && application.getNdgStatus().equalsIgnoreCase(GepafinConstant.NDG_GENERATED) && application.getNdg() != null) {
|
||||
ndgResponse.setNdg(application.getNdg());
|
||||
return ndgResponse;
|
||||
}
|
||||
|
||||
// Update application status
|
||||
application.setNdgStatus(GepafinConstant.NDG_IN_PROGRESS);
|
||||
applicationRepository.save(application);
|
||||
|
||||
// Start async processing
|
||||
startAsyncNdgProcessing(applicationId);
|
||||
|
||||
throw new CustomValidationException(Status.SUCCESS, Translator.toLocale(GepafinConstant.NDG_GENERATION_IS_IN_PROGRESS));
|
||||
}
|
||||
|
||||
private void startAsyncNdgProcessing(Long applicationId) {
|
||||
// Check if a thread is already running for this application
|
||||
if (executorMap.containsKey(applicationId)) {
|
||||
log.warn("Async processing already running for applicationId: {}", applicationId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a dedicated thread for asynchronous processing
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable);
|
||||
thread.setName("AsyncNdgProcessing-" + applicationId);
|
||||
return thread;
|
||||
});
|
||||
executorMap.put(applicationId, executor);
|
||||
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
log.info("Starting async processing for applicationId: {}", applicationId);
|
||||
processNdgGeneration(applicationId);
|
||||
} catch (Exception e) {
|
||||
log.error("Error in async NDG processing for applicationId: {}", applicationId, e);
|
||||
} finally {
|
||||
// Cleanup resources
|
||||
ExecutorService executorToShutdown = executorMap.remove(applicationId);
|
||||
if (executorToShutdown != null) {
|
||||
executorToShutdown.shutdown();
|
||||
}
|
||||
log.info("Async processing completed for applicationId: {}", applicationId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void processNdgGeneration(Long applicationId) {
|
||||
// Validate application, company, and hub
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
|
||||
HubEntity hub = hubRepository.findByHubId(application.getHubId());
|
||||
|
||||
if (!hub.getUniqueUuid().equals(defaultHubUuid)) {
|
||||
log.info("Ndg cannot be created for another Hub, it is default for Gepafin.");
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.NO_NDG_FOR_ANOTHER_HUB));
|
||||
}
|
||||
|
||||
try {
|
||||
// Authenticate and fetch token if required
|
||||
if (hub.getAppointmentAuthTokenId() == null || hub.getAreaCode() == null) {
|
||||
authenticateAndSaveToken(hub);
|
||||
}
|
||||
|
||||
String authorizationToken = getBearerToken(hub);
|
||||
|
||||
// Try retrieving NDG by VAT number
|
||||
AppointmentLoginResponse ndgResponse = retrieveNdgByVatNumber(company.getVatNumber(), authorizationToken, hub, application);
|
||||
if (isNdgValid(ndgResponse.getNdg())) {
|
||||
saveNdgAndIdVisura(application, company, ndgResponse.getNdg(), null);
|
||||
log.info("NDG successfully generated for applicationId: {}", applicationId);
|
||||
} else {
|
||||
// If NDG isn't immediately available, start polling
|
||||
handleNdgPolling(application, company, hub, authorizationToken);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error during NDG generation for applicationId: {}", applicationId, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleNdgPolling(ApplicationEntity application, CompanyEntity company, HubEntity hub, String authorizationToken) {
|
||||
|
||||
try {
|
||||
log.info("Starting NDG polling for applicationId: {}", application.getId());
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
while (true) {
|
||||
if (application.getNdg() != null) {
|
||||
log.info("NDG retrieved for applicationId: {}", application.getId());
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch Visura list and attempt to parse NDG
|
||||
String visuraListJson = getVisuraList(application.getIdVisura(), authorizationToken, application, hub);
|
||||
String ndg = parseNdgFromVisuraListResponse(visuraListJson);
|
||||
|
||||
if (isNdgValid(ndg)) {
|
||||
// CompanyEntity oldCompanyData = Utils.getClonedEntityForData(company);
|
||||
// ApplicationEntity oldApplicationData = Utils.getClonedEntityForData(application);
|
||||
|
||||
company.setNdg(ndg);
|
||||
application.setNdg(ndg);
|
||||
application.setNdgStatus(GepafinConstant.NDG_GENERATED);
|
||||
application.setStatus(ApplicationStatusTypeEnum.NDG.getValue());
|
||||
applicationRepository.save(application);
|
||||
companyRepository.save(company);
|
||||
log.info("NDG saved successfully for applicationId: {}", application.getId());
|
||||
|
||||
// /** This code is responsible for adding a version history log for the "update application ndg code, status, and Id visura"
|
||||
// operation. **/
|
||||
// loggingUtil.addVersionHistory(
|
||||
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationData)
|
||||
// .newData(application).build());
|
||||
//
|
||||
// /** This code is responsible for adding a version history log for the "update company ndg code" operation. **/
|
||||
// loggingUtil.addVersionHistory(
|
||||
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCompanyData)
|
||||
// .newData(company).build());
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if polling has timed out
|
||||
if (System.currentTimeMillis() - startTime > TimeUnit.HOURS.toMillis(2)) {
|
||||
log.warn("NDG polling timed out for applicationId: {}", application.getId());
|
||||
application.setNdgStatus(GepafinConstant.NDG_FAILED);
|
||||
applicationRepository.save(application);
|
||||
break;
|
||||
}
|
||||
|
||||
// Wait before the next polling attempt
|
||||
Thread.sleep(TimeUnit.MINUTES.toMillis(15));
|
||||
} catch (InterruptedException e) {
|
||||
log.warn("NDG polling interrupted for applicationId: {}", application.getId());
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("Error during NDG polling for applicationId: {}", application.getId(), e);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
log.info("NDG polling completed for applicationId: {}", application.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private static String getBearerToken(HubEntity hub) {
|
||||
|
||||
return "Bearer " + hub.getAppointmentAuthTokenId();
|
||||
}
|
||||
|
||||
private boolean isNdgValid(String ndg) {
|
||||
|
||||
return ndg != null && !ndg.isEmpty();
|
||||
}
|
||||
|
||||
private void saveNdgAndIdVisura(ApplicationEntity application, CompanyEntity company, String ndg, String idVisura) {
|
||||
|
||||
//cloned for old application and company data
|
||||
// ApplicationEntity oldApplicationData = Utils.getClonedEntityForData(application);
|
||||
// CompanyEntity oldCompanyData = Utils.getClonedEntityForData(company);
|
||||
|
||||
application.setNdg(ndg);
|
||||
application.setIdVisura(idVisura);
|
||||
application.setNdgStatus(GepafinConstant.NDG_GENERATED);
|
||||
application.setStatus(ApplicationStatusTypeEnum.NDG.getValue());
|
||||
company.setNdg(ndg);
|
||||
companyRepository.save(company);
|
||||
applicationRepository.save(application);
|
||||
Map<String ,String> placeHolders=notificationDao.sendNotificationToBeneficiary(application,NotificationTypeEnum.NDG_GENERATION);
|
||||
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.NDG_GENERATION);
|
||||
|
||||
// /** This code is responsible for adding a version history log for the "update application ndg code, status, and Id visura" operation. **/
|
||||
// loggingUtil.addVersionHistory(
|
||||
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationData).newData(application).build());
|
||||
//
|
||||
// /** This code is responsible for adding a version history log for the "update company ndg code" operation. **/
|
||||
// loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCompanyData).newData
|
||||
// (company).build());
|
||||
|
||||
log.info("NDG saved for applicationId: {}, {}", application.getId(), application.getNdg());
|
||||
}
|
||||
|
||||
private String getVisuraList(String idVisura, String authorizationToken, ApplicationEntity application, HubEntity hub) {
|
||||
|
||||
AppointmentVisuraListRequest visuraListRequest = new AppointmentVisuraListRequest();
|
||||
AppointmentVisuraListRequest.VisuraFilter filter = new AppointmentVisuraListRequest.VisuraFilter();
|
||||
filter.setIdVisura(idVisura);
|
||||
visuraListRequest.setFilter(filter);
|
||||
|
||||
try {
|
||||
String requestJson = Utils.convertObjectToJson(visuraListRequest);
|
||||
ResponseEntity<Object> response = appointmentApiService.getVisuraList(requestJson, authorizationToken);
|
||||
return Utils.convertObjectToJson(response.getBody());
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
log.error("403 Forbidden received while getting visuraList for Ndg code. Regenerating token...");
|
||||
// Regenerate the token and retry
|
||||
String newAuthorizationToken = regenerateTokenAndSave(hub);
|
||||
return getVisuraList(idVisura, newAuthorizationToken, application, hub);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to fetch Ndg code: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Error fetching Ndg List", e);
|
||||
}
|
||||
}
|
||||
|
||||
private HubEntity authenticateAndSaveToken(HubEntity hub) {
|
||||
|
||||
// HubEntity oldHubData = Utils.getClonedEntityForData(hub);
|
||||
try {
|
||||
//code to generate token with payload having "iat" epoch timestamp and secret key with no expiry and send in below method call
|
||||
String authJwtToken = Utils.generateAuthTokenForLoginToOdessa();
|
||||
log.info("Got the auth for login to odessa {}", authJwtToken);
|
||||
hub.setAuthToken(authJwtToken);
|
||||
hubRepository.save(hub);
|
||||
|
||||
// /** This code is responsible for adding a version history log for the "Updating auth token for login api in hub" operation. **/
|
||||
// loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldHubData).newData
|
||||
// (hub).build());
|
||||
|
||||
// Prepare the request body (adjust if necessary for login API)
|
||||
Map<String, Object> body = Collections.emptyMap();
|
||||
// Perform login API call
|
||||
ResponseEntity<Object> responseLogin = appointmentApiService.loginWithOdessa(authJwtToken, source, context, user, password, body);
|
||||
|
||||
// Handle successful login
|
||||
if (responseLogin.getStatusCode() == HttpStatus.OK) {
|
||||
log.info("Login successful to odessa. Parsing response.");
|
||||
String loginResponseJson = Utils.convertObjectToJson(responseLogin.getBody());
|
||||
AppointmentLoginResponse parsedResponse = parseLoginResponse(loginResponseJson);
|
||||
|
||||
// Validate and save token
|
||||
if (parsedResponse.getTokenId() != null) {
|
||||
hub.setAppointmentAuthTokenId(parsedResponse.getTokenId());
|
||||
hub.setAreaCode(parsedResponse.getAreaCode());
|
||||
hubRepository.save(hub);
|
||||
|
||||
// /** This code is responsible for adding a version history log for the "inserting token and areaCode from login odessa response for
|
||||
// appointment flow api's"
|
||||
// * operation. **/
|
||||
// loggingUtil.addVersionHistory(
|
||||
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldHubData).newData(hub)
|
||||
// .build());
|
||||
|
||||
log.info("Saved new authToken and areaCode for Hub.");
|
||||
return hub;
|
||||
} else {
|
||||
throw new RuntimeException("Login response is missing a valid tokenId for login to odessa system, please try again.");
|
||||
}
|
||||
}
|
||||
// Handle non-OK response
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.ERROR_IN_GENERATING_NDG_TRY_AGAIN));
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to authenticate user on Odessa : {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Authentication failed on Odessa. try again", e);
|
||||
}
|
||||
}
|
||||
|
||||
private AppointmentLoginResponse retrieveNdgByVatNumber(String vatNumber, String authorizationToken, HubEntity hub, ApplicationEntity application) {
|
||||
|
||||
try {
|
||||
// Prepare the NDG request
|
||||
AppointmentNdgRequest ndgRequest = getAppointmentNdgRequest(vatNumber);
|
||||
// Call the API to retrieve NDG
|
||||
ResponseEntity<Object> response = appointmentApiService.getNdgByVatNumber(ndgRequest, authorizationToken);
|
||||
String responseJson = Utils.convertObjectToJson(response.getBody());
|
||||
// Parse and return the NDG response
|
||||
return parseNdgResponse(responseJson);
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
logForbiddenError();
|
||||
// Regenerate the token and retry
|
||||
String newAuthorizationToken = regenerateTokenAndSave(hub);
|
||||
return retrieveNdgByVatNumber(vatNumber, newAuthorizationToken, hub, application);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to retrieve NDG by VAT number: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("NDG retrieval failed.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String regenerateTokenAndSave(HubEntity hub) {
|
||||
|
||||
try {
|
||||
hub = authenticateAndSaveToken(hub);
|
||||
return "Bearer " + hub.getAppointmentAuthTokenId();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate token from Odessa: {}", e.getMessage());
|
||||
throw new RuntimeException("Token regeneration failed from Odessa.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private AppointmentLoginResponse createVisura(CompanyEntity company, String authorizationToken, HubEntity hub) {
|
||||
|
||||
try {
|
||||
String visuraRequest = getAppointmentVisuraRequest(company, hub.getAreaCode());
|
||||
ResponseEntity<Object> response = appointmentApiService.createVisura(visuraRequest, authorizationToken);
|
||||
String responseJson = Utils.convertObjectToJson(response.getBody());
|
||||
return parseVisuraResponse(responseJson);
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
logForbiddenError();
|
||||
// Regenerate the token and retry
|
||||
String newAuthorizationToken = regenerateTokenAndSave(hub);
|
||||
return createVisura(company, newAuthorizationToken, hub);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create Visura for Ndg : {}", e.getMessage());
|
||||
throw new RuntimeException("Visura creation failed for Ndg.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void logForbiddenError() {
|
||||
|
||||
log.error("403 Forbidden received while retrieving NDG. Regenerating token...");
|
||||
}
|
||||
|
||||
private static AppointmentNdgRequest getAppointmentNdgRequest(String vatNumber) {
|
||||
|
||||
AppointmentNdgRequest request = new AppointmentNdgRequest();
|
||||
AppointmentNdgRequest.Filter filter = new AppointmentNdgRequest.Filter();
|
||||
filter.setPartitaIva(vatNumber);
|
||||
|
||||
AppointmentNdgRequest.Pagination pagination = new AppointmentNdgRequest.Pagination();
|
||||
pagination.setTargetPage(AppointmentApiConstant.TARGET_PAGE_SIZE);
|
||||
pagination.setRecordsPerPage(AppointmentApiConstant.RECORD_PER_PAGE_SIZE);
|
||||
|
||||
request.setFilter(filter);
|
||||
request.setPagination(pagination);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static String getAppointmentVisuraRequest(CompanyEntity company, String areaCode) {
|
||||
|
||||
AppointmentVisuraRequest visuraRequest = new AppointmentVisuraRequest();
|
||||
AppointmentVisuraRequest.VisuraInput input = new AppointmentVisuraRequest.VisuraInput();
|
||||
input.setPartitaIva(company.getVatNumber());
|
||||
input.setCodiceFiscale(company.getCodiceFiscale());
|
||||
input.setCodArea(areaCode);
|
||||
input.setVisuraMode(AppointmentApiConstant.VISURA_MODE);
|
||||
input.setVisuraProvider(AppointmentApiConstant.VISURA_PROVIDER);
|
||||
input.setCodAgente(AppointmentApiConstant.COD_AGENTE);
|
||||
input.setAnagraficaLegame(AppointmentApiConstant.IS_ANAGRAFICA_LEGAME);
|
||||
input.setCreaAnagrafica(AppointmentApiConstant.CREA_ANAGRAFICA);
|
||||
input.setFromRating(AppointmentApiConstant.IS_FROM_RATING);
|
||||
input.setSalvaDocumenti(AppointmentApiConstant.SALVA_DOCUMENTI);
|
||||
input.setVisuraType(AppointmentApiConstant.VISURA_TYPE);
|
||||
visuraRequest.setInput(input);
|
||||
return Utils.convertObjectToJson(visuraRequest);
|
||||
}
|
||||
|
||||
private String parseNdgFromVisuraListResponse(String jsonResponse) {
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode rootNode = objectMapper.readTree(jsonResponse);
|
||||
JsonNode dataNode = rootNode.get(GepafinConstant.DATA_STRING);
|
||||
|
||||
if (dataNode != null && dataNode.isArray() && dataNode.size() > 0) {
|
||||
JsonNode firstEntry = dataNode.get(0);
|
||||
JsonNode ndgClienteNode = firstEntry.get("ndgCliente");
|
||||
if (ndgClienteNode != null && ndgClienteNode.get("code") != null) {
|
||||
String code = ndgClienteNode.get("code").asText();
|
||||
return normalizeNullValue(code);
|
||||
}
|
||||
}
|
||||
log.warn("NDG not found in Visura List API response.");
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to parse NDG from Visura List API response: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Error parsing NDG from Visura List API response", e);
|
||||
}
|
||||
}
|
||||
|
||||
public AppointmentLoginResponse parseLoginResponse(String jsonResponse) {
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode rootNode = objectMapper.readTree(jsonResponse);
|
||||
JsonNode dataNode = rootNode.get(GepafinConstant.DATA_STRING);
|
||||
|
||||
if (dataNode != null) {
|
||||
AppointmentLoginResponse response = new AppointmentLoginResponse();
|
||||
response.setTokenId(dataNode.get("tokenId").asText());
|
||||
JsonNode areasNode = dataNode.get("areas");
|
||||
if (areasNode != null && areasNode.isArray() && areasNode.size() > 0) {
|
||||
response.setAreaCode(areasNode.get(0).get("code").asText());
|
||||
}
|
||||
response.setCompanyId(dataNode.get("companyId").asLong());
|
||||
return response;
|
||||
} else {
|
||||
throw new RuntimeException("Invalid JSON structure: Missing 'data' node.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to parse response from loginApi for odessa: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public AppointmentLoginResponse parseVisuraResponse(String jsonResponse) {
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode rootNode = objectMapper.readTree(jsonResponse);
|
||||
JsonNode dataNode = rootNode.get(GepafinConstant.DATA_STRING);
|
||||
|
||||
if (dataNode != null) {
|
||||
AppointmentLoginResponse response = new AppointmentLoginResponse();
|
||||
response.setIdVisura(normalizeNullValue(dataNode.get(GepafinConstant.ID_VISURA_STRING).asText()));
|
||||
response.setNdg(normalizeNullValue(dataNode.get(GepafinConstant.NDG_STRING).asText()));
|
||||
return response;
|
||||
} else {
|
||||
throw new RuntimeException("Invalid JSON structure: Missing 'data' node.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to parse response: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public AppointmentLoginResponse parseNdgResponse(String jsonResponse) {
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode rootNode = objectMapper.readTree(jsonResponse);
|
||||
JsonNode dataArray = rootNode.get(GepafinConstant.DATA_STRING);
|
||||
if (dataArray == null || !dataArray.isArray() || dataArray.isEmpty()) {
|
||||
log.info("NDG data is empty or missing in the response.");
|
||||
AppointmentLoginResponse emptyResponse = new AppointmentLoginResponse();
|
||||
emptyResponse.setNdg(null);
|
||||
return emptyResponse;
|
||||
}
|
||||
JsonNode firstDataEntry = dataArray.get(0);
|
||||
AppointmentLoginResponse response = new AppointmentLoginResponse();
|
||||
if (firstDataEntry.has(GepafinConstant.NDG_STRING)) {
|
||||
response.setNdg(normalizeNullValue(firstDataEntry.get(GepafinConstant.NDG_STRING).asText()));
|
||||
}
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to parse response: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Failed to parse NDG response.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeNullValue(String value) {
|
||||
|
||||
return (value == null || GepafinConstant.NULL_STRING.equalsIgnoreCase(value.trim())) ? null : value;
|
||||
}
|
||||
|
||||
public AppointmentCreationResponse createAppointment(Long applicationId, CreateAppointmentRequest createAppointmentRequest) {
|
||||
// Validate the application
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
|
||||
AppointmentCreationResponse appointmentCreationResponse = new AppointmentCreationResponse();
|
||||
|
||||
ApplicationEntity oldApplicationData = Utils.getClonedEntityForData(application);
|
||||
HubEntity hub = hubRepository.findByHubId(application.getHubId());
|
||||
|
||||
// Check hub UUID and enforce constraints
|
||||
if (!hub.getUniqueUuid().equals(defaultHubUuid)) {
|
||||
log.info("Appointment cannot be created for another Hub; default is required for Gepafin.");
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.NO_APPOINTMENT_FOR_ANOTHER_HUB));
|
||||
}
|
||||
|
||||
try {
|
||||
// Pre-check conditions for appointment creation
|
||||
if (application.getNdg() != null && !Objects.equals(application.getNdgStatus(), GepafinConstant.NDG_IN_PROGRESS) && application.getAppointmentId() != null) {
|
||||
appointmentCreationResponse.setAppointmentId(application.getAppointmentId());
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPOINTMENT_ALREADY_CREATED));
|
||||
// return appointmentCreationResponse;
|
||||
}
|
||||
|
||||
if (application.getNdg() == null && Objects.equals(application.getNdgStatus(), GepafinConstant.NDG_IN_PROGRESS)) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.NDG_NOT_FOUND_FOR_APPLICATION));
|
||||
}
|
||||
|
||||
// Generate authorization token and fetch template data
|
||||
String authorizationToken = getBearerToken(hub);
|
||||
ResponseEntity<Object> response = appointmentApiService.getAppointmentTemplateForTemplateCreation(authorizationToken);
|
||||
|
||||
if (response.getStatusCode() != HttpStatus.OK) {
|
||||
log.error("Failed to retrieve appointment template for appointment creation. Status: {}", response.getStatusCode());
|
||||
throw new IllegalStateException("Failed to retrieve appointment template for appointment creation");
|
||||
}
|
||||
|
||||
// Parse template data
|
||||
String responseDataForTemplate = Utils.convertObjectToJson(response.getBody());
|
||||
AppointmentCreationRequest templateRichiestaData = parseTemplateResponseData(responseDataForTemplate);
|
||||
|
||||
// Build the appointment request body
|
||||
AppointmentCreationRequest appointmentCreationRequest = buildAppointmentCreationRequest(applicationId, createAppointmentRequest, hub.getAreaCode(),
|
||||
templateRichiestaData);
|
||||
String appointmentRequestBody = Utils.convertObjectToJson(appointmentCreationRequest);
|
||||
|
||||
// Make API call to create the appointment
|
||||
ResponseEntity<Object> appointmentResponse = appointmentApiService.createAppointment(authorizationToken, context, appointmentRequestBody);
|
||||
String appointmentId = extractAppointmentIdFromResponse(appointmentResponse);
|
||||
|
||||
if (appointmentId != null) {
|
||||
// Update application with the appointment ID
|
||||
application.setAppointmentId(appointmentId);
|
||||
application.setStatus(ApplicationStatusTypeEnum.APPOINTMENT.getValue());
|
||||
applicationRepository.save(application);
|
||||
|
||||
// Log version history
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationData).newData(application).build());
|
||||
}
|
||||
|
||||
appointmentCreationResponse.setAppointmentId(appointmentId);
|
||||
return appointmentCreationResponse;
|
||||
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
log.error("403 Forbidden received while retrieving template. Regenerating token...");
|
||||
regenerateTokenAndSave(hub);
|
||||
return createAppointment(applicationId, createAppointmentRequest);
|
||||
}
|
||||
}
|
||||
|
||||
private String extractAppointmentIdFromResponse(ResponseEntity<Object> appointmentResponse) {
|
||||
|
||||
if (appointmentResponse.getBody() != null) {
|
||||
Map<String, Object> responseBody = (Map<String, Object>) appointmentResponse.getBody();
|
||||
if (responseBody.containsKey(GepafinConstant.DATA_STRING)) {
|
||||
Map<String, Object> data = (Map<String, Object>) responseBody.get(GepafinConstant.DATA_STRING);
|
||||
if (data != null && data.containsKey(GepafinConstant.ID_STRING)) {
|
||||
return data.get(GepafinConstant.ID_STRING).toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public AppointmentCreationRequest parseTemplateResponseData(String jsonResponse) {
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode rootNode = objectMapper.readTree(jsonResponse);
|
||||
JsonNode richiestaClienteArray = rootNode.path(GepafinConstant.DATA_STRING).path(GepafinConstant.RICHIESTA_CLIENTE_STRING);
|
||||
|
||||
AppointmentCreationRequest appointmentCreationRequest = new AppointmentCreationRequest();
|
||||
AppointmentCreationRequest.Input input = new AppointmentCreationRequest.Input();
|
||||
|
||||
// Map `richiestaCliente` array
|
||||
List<AppointmentCreationRequest.RichiestaCliente> richiestaClienteList = new ArrayList<>();
|
||||
if (richiestaClienteArray.isArray()) {
|
||||
for (JsonNode richiestaNode : richiestaClienteArray) {
|
||||
richiestaClienteList.add(objectMapper.treeToValue(richiestaNode, AppointmentCreationRequest.RichiestaCliente.class));
|
||||
}
|
||||
}
|
||||
|
||||
input.setRichiestaCliente(richiestaClienteList);
|
||||
appointmentCreationRequest.setInput(input);
|
||||
return appointmentCreationRequest;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error parsing template response: {}", e.getMessage(), e);
|
||||
throw new IllegalStateException("Failed to parse template response", e);
|
||||
}
|
||||
}
|
||||
|
||||
public AppointmentCreationRequest buildAppointmentCreationRequest(Long applicationId, CreateAppointmentRequest createAppointmentRequest, String areaCode,
|
||||
AppointmentCreationRequest templateRichiestaData) {
|
||||
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
CreateAppointmentRequest.Nota nota = createAppointmentRequest.getNota();
|
||||
|
||||
AppointmentCreationRequest appointmentCreationRequest = new AppointmentCreationRequest();
|
||||
AppointmentCreationRequest.Input input = new AppointmentCreationRequest.Input();
|
||||
|
||||
// Set Input Fields
|
||||
input.setId(areaCode);
|
||||
input.setNdg(application.getNdg());
|
||||
|
||||
// Populate richiestaCliente from template data
|
||||
List<AppointmentCreationRequest.RichiestaCliente> richiestaClienteList = new ArrayList<>();
|
||||
for (AppointmentCreationRequest.RichiestaCliente templateRichiesta : templateRichiestaData.getInput().getRichiestaCliente()) {
|
||||
AppointmentCreationRequest.RichiestaCliente richiestaCliente = new AppointmentCreationRequest.RichiestaCliente();
|
||||
BeanUtils.copyProperties(templateRichiesta, richiestaCliente);
|
||||
|
||||
// Add specific `nota`
|
||||
AppointmentCreationRequest.Nota requestNota = new AppointmentCreationRequest.Nota();
|
||||
requestNota.setTitolo(nota.getTitolo());
|
||||
requestNota.setTesto(nota.getTesto());
|
||||
richiestaCliente.setNota(requestNota);
|
||||
|
||||
richiestaClienteList.add(richiestaCliente);
|
||||
}
|
||||
|
||||
input.setRichiestaCliente(richiestaClienteList);
|
||||
appointmentCreationRequest.setInput(input);
|
||||
return appointmentCreationRequest;
|
||||
}
|
||||
|
||||
public DocumentUploadResponse uploadDocumentToExternalSystem(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
|
||||
// Check if the document is already being processed
|
||||
DocumentEntity systemDoc = documentDao.validateDocument(documentId);
|
||||
|
||||
Claims claims = tokenProvider.getClaimsFromToken(tokenProvider.extractTokenFromRequest(request));
|
||||
Long hubId = Utils.extractHubIdFromPayload(claims.getSubject());
|
||||
if (systemDoc.getDocumentAttachmentId() != null) {
|
||||
// If the documentAttachmentId is already set, return the response
|
||||
log.info("Document already uploaded with documentAttachmentId: {}", systemDoc.getDocumentAttachmentId());
|
||||
DocumentUploadResponse response = new DocumentUploadResponse();
|
||||
response.setDocumentAttachmentId(systemDoc.getDocumentAttachmentId());
|
||||
return response;
|
||||
}
|
||||
// Check if a thread is already running for this document upload
|
||||
if (threadForDocumentMap.containsKey(documentId)) {
|
||||
log.warn("Document upload already running for documentId: {}", documentId);
|
||||
throw new CustomValidationException(Status.SUCCESS, Translator.toLocale(GepafinConstant.DOCUMENT_UPLOADING_IN_PROGRESS));
|
||||
}
|
||||
// Start the upload process in the background
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable);
|
||||
thread.setName(GepafinConstant.ASYNC_DOCUMENT_UPLOAD_NAME + documentId);
|
||||
return thread;
|
||||
});
|
||||
threadForDocumentMap.put(documentId, executor);
|
||||
|
||||
executor.submit(() -> {
|
||||
threadLocalHubId.set(hubId);
|
||||
try {
|
||||
log.info("Starting async document upload for documentId: {}", documentId);
|
||||
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest);
|
||||
} catch (Exception e) {
|
||||
log.error("Error in async document upload for documentId: {}", documentId, e);
|
||||
} finally {
|
||||
// Cleanup resources
|
||||
ExecutorService executorToShutdown = threadForDocumentMap.remove(documentId);
|
||||
if (executorToShutdown != null) {
|
||||
executorToShutdown.shutdown();
|
||||
threadLocalHubId.remove();
|
||||
}
|
||||
log.info("Async document upload completed for documentId: {}", documentId);
|
||||
}
|
||||
});
|
||||
return null;
|
||||
// Return an immediate response indicating the process is in progress
|
||||
// throw new CustomValidationException(Status.SUCCESS, Translator.toLocale(GepafinConstant.DOCUMENT_UPLOADING_IN_PROGRESS));
|
||||
}
|
||||
|
||||
private void uploadDocumentToExternalSystemSync(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
|
||||
// Synchronous upload logic
|
||||
DocumentEntity systemDoc = documentDao.validateDocument(documentId);
|
||||
|
||||
Long hubId = threadLocalHubId.get();
|
||||
HubEntity hub = hubRepository.findByHubId(hubId);
|
||||
|
||||
if (!hub.getUniqueUuid().equals(defaultHubUuid)) {
|
||||
log.info("Document cannot be uploaded for another Hub, it is default for Gepafin.");
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.NO_DOCUMENT_UPLOAD_FOR_ANOTHER_HUB));
|
||||
}
|
||||
|
||||
log.info("Got Document in system: {}", systemDoc);
|
||||
String oldUrl = systemDoc.getFilePath();
|
||||
String authorizationToken = getBearerToken(hub);
|
||||
|
||||
try {
|
||||
File localFile = downloadFileFromS3(oldUrl);
|
||||
MultipartFile multipartFile = convertFileToMultipartFile(localFile);
|
||||
|
||||
UploadDocToExternalSystemRequest externalSystemRequest = new UploadDocToExternalSystemRequest();
|
||||
externalSystemRequest.setInput(getUploadDocumentInput(docToExternalSystemRequest));
|
||||
|
||||
String uploadDocRequest = Utils.convertObjectToJson(externalSystemRequest);
|
||||
ResponseEntity<Object> uploadedDocumentData = appointmentApiService.uploadDocumentToExternalSystemForAppointment(authorizationToken, context, uploadDocRequest,
|
||||
multipartFile);
|
||||
|
||||
String responseData = Utils.convertObjectToJson(uploadedDocumentData.getBody());
|
||||
DocumentUploadResponse parsedResponse = parseDocumentUploadResponse(responseData);
|
||||
|
||||
if (parsedResponse == null) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.ERROR_UPLOADING_DOCUMENT));
|
||||
}
|
||||
|
||||
// Save the documentAttachmentId to the database
|
||||
systemDoc.setDocumentAttachmentId(parsedResponse.getDocumentAttachmentId());
|
||||
documentRepository.save(systemDoc);
|
||||
|
||||
log.info("Document uploaded successfully to external system: {}", parsedResponse);
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
log.error("403 Forbidden received while uploading document. Regenerating token...");
|
||||
regenerateTokenAndSave(hub);
|
||||
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest);
|
||||
} catch (Exception e) {
|
||||
log.error("Exception during document upload: {}", e.getMessage(), e);
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.EXTERNAL_DOCUMENT_UPLOAD_FAILURE_MSG));
|
||||
}
|
||||
}
|
||||
|
||||
private UploadDocToExternalSystemRequest.Input getUploadDocumentInput(UploadDocToExternalSystemRequest docToExternalSystemRequest) {
|
||||
|
||||
UploadDocToExternalSystemRequest.Input input = new UploadDocToExternalSystemRequest.Input();
|
||||
input.setIdTipoProtocollo(docToExternalSystemRequest.getInput().getIdTipoProtocollo());
|
||||
input.setIdClassificazione(docToExternalSystemRequest.getInput().getIdClassificazione());
|
||||
input.setFlagDaFirmare(flagDaFirmare);
|
||||
input.setDescrizione(docToExternalSystemRequest.getInput().getDescrizione());
|
||||
|
||||
UploadDocToExternalSystemRequest.Input.Attributes attributes = new UploadDocToExternalSystemRequest.Input.Attributes();
|
||||
attributes.setNdg(docToExternalSystemRequest.getInput().getAttributes().getNdg());
|
||||
attributes.setEmail(docToExternalSystemRequest.getInput().getAttributes().getEmail());
|
||||
|
||||
input.setAttributes(attributes);
|
||||
return input;
|
||||
}
|
||||
|
||||
public static MultipartFile convertFileToMultipartFile(File file) throws IOException {
|
||||
|
||||
FileInputStream input = new FileInputStream(file);
|
||||
return new MockMultipartFile(file.getName(), file.getName(), MediaType.APPLICATION_OCTET_STREAM_VALUE, input);
|
||||
}
|
||||
|
||||
private File downloadFileFromS3(String fileUrl) throws Exception {
|
||||
|
||||
String key = extractS3KeyFromUrl(fileUrl);
|
||||
File localFile = new File(GepafinConstant.TEMP_FILE_PATH + extractFileName(key));
|
||||
|
||||
GetObjectRequest getObjectRequest = new GetObjectRequest(OLD_BUCKET, key);
|
||||
|
||||
try (InputStream s3Stream = s3Client.getObject(getObjectRequest).getObjectContent(); FileOutputStream outputStream = new FileOutputStream(localFile)) {
|
||||
s3Stream.transferTo(outputStream);
|
||||
}
|
||||
|
||||
log.info("Downloaded file from old S3 bucket: {}", key);
|
||||
return localFile;
|
||||
}
|
||||
|
||||
private String extractS3KeyFromUrl(String url) {
|
||||
|
||||
return url.replace(s3Url, "");
|
||||
}
|
||||
|
||||
private String extractFileName(String filePath) {
|
||||
|
||||
String[] parts = filePath.split("/");
|
||||
return parts[parts.length - 1];
|
||||
|
||||
}
|
||||
|
||||
public DocumentUploadResponse parseDocumentUploadResponse(String jsonResponse) {
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode rootNode = objectMapper.readTree(jsonResponse);
|
||||
|
||||
// Navigate to the "data" node
|
||||
JsonNode dataNode = rootNode.get(GepafinConstant.DATA_STRING);
|
||||
if (dataNode != null) {
|
||||
DocumentUploadResponse response = new DocumentUploadResponse();
|
||||
|
||||
// Extract "documentAttachmentId"
|
||||
JsonNode documentAttachmentIdNode = dataNode.get(GepafinConstant.DOCUMENT_ATTACHMENT_ID_STRING);
|
||||
if (documentAttachmentIdNode != null) {
|
||||
response.setDocumentAttachmentId(documentAttachmentIdNode.asText());
|
||||
} else {
|
||||
throw new RuntimeException("Invalid JSON structure: Missing 'documentAttachmentId' node.");
|
||||
}
|
||||
|
||||
return response;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to parse response: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
|
||||
@@ -226,7 +227,7 @@ public class AssignedApplicationsDao {
|
||||
|
||||
|
||||
public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request,
|
||||
Long id, AssignedApplicationsRequest updateRequest) {
|
||||
Long id, UpdateAssignedApplicationRequest updateRequest) {
|
||||
UserEntity updatedByUser = validator.validateUser(request);
|
||||
log.info("Updating assigned application with ID: {}", id);
|
||||
AssignedApplicationsEntity existingAssignment = validateAssignedApplication(id);
|
||||
@@ -237,7 +238,9 @@ public class AssignedApplicationsDao {
|
||||
setIfUpdated(existingAssignment::getNote, existingAssignment::setNote, updateRequest.getNote());
|
||||
setIfUpdated(existingAssignment::getStatus, existingAssignment::setStatus, updateRequest.getStatus().name());
|
||||
setIfUpdated(existingAssignment::getAssignedBy, existingAssignment::setAssignedBy, updatedByUser.getId());
|
||||
|
||||
setIfUpdated(existingAssignment::getUserId, existingAssignment::setUserId, updateRequest.getUserId());
|
||||
Optional<ApplicationEvaluationEntity> entityOptional = applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(id);
|
||||
entityOptional.ifPresent(applicationEvaluationEntity -> setIfUpdated(applicationEvaluationEntity::getUserId, applicationEvaluationEntity::setUserId, updateRequest.getUserId()));
|
||||
existingAssignment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
|
||||
AssignedApplicationsEntity updatedAssignment = saveAssignedApplication(existingAssignment, oldAssignedApplicationEntity, VersionActionTypeEnum.UPDATE);
|
||||
|
||||
@@ -15,7 +15,9 @@ import java.util.zip.ZipOutputStream;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.NotificationReq;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.model.response.*;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
@@ -49,6 +51,7 @@ 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;
|
||||
import static org.hibernate.internal.util.collections.CollectionHelper.listOf;
|
||||
|
||||
@Component
|
||||
public class CallDao {
|
||||
@@ -108,6 +111,15 @@ public class CallDao {
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Autowired
|
||||
private BeneficiaryRepository beneficiaryRepository;
|
||||
|
||||
@Autowired
|
||||
private NotificationTypeRepository notificationTypeRepository;
|
||||
|
||||
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
|
||||
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
|
||||
CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
|
||||
@@ -828,10 +840,20 @@ public class CallDao {
|
||||
validateStatusChange(currentStatus, statusReq);
|
||||
callEntity.setStatus(statusReq.getValue());
|
||||
callEntity = callRepository.save(callEntity);
|
||||
|
||||
|
||||
//Creating notification.
|
||||
List<Long> userIds = beneficiaryRepository.findUserIdsByHubIdAndBeneficiaryId(callEntity.getHub().getId());
|
||||
Map<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("{{call_name}}", callEntity.getName());
|
||||
userIds.forEach(userId -> {
|
||||
List<Long> companyIds = notificationDao.getAllCompanyIdsForUser(userId);
|
||||
NotificationReq notificationReq = notificationDao.createNotificationReq(NotificationTypeEnum.CALL_CREATED.getValue(), placeholders, userId, null, companyIds);
|
||||
notificationDao.sendNotification(notificationReq);
|
||||
});
|
||||
|
||||
/** This code is responsible for adding a version history log for the "update call status" operation **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCallEntity).newData(callEntity).build());
|
||||
|
||||
|
||||
return convertToCallResponseBean(callEntity);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,13 +5,14 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.enums.DocOtherSourceTypeEnum;
|
||||
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserWithCompanyRepository;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
@@ -33,6 +34,7 @@ import net.gepafin.tendermanagement.model.response.UserResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserCompanyDelegationRepository;
|
||||
import net.gepafin.tendermanagement.service.AmazonS3Service;
|
||||
import net.gepafin.tendermanagement.service.ApplicationEvaluationService;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
@@ -82,6 +84,12 @@ public class DelegationDao {
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationService applicationEvaluationService;
|
||||
|
||||
public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) {
|
||||
try {
|
||||
String s3Folder = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.TEMPLATE, 0L, 0L,0L);
|
||||
@@ -257,12 +265,12 @@ public class DelegationDao {
|
||||
}
|
||||
}
|
||||
|
||||
public CompanyDelegationResponse getCompanyDelegation(UserEntity userEntity, Long companyId) {
|
||||
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyId);
|
||||
public CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId, Long applicationId) {
|
||||
|
||||
UserWithCompanyEntity userWithCompanyEntity= validateUserAndGetUserWithCompany(request, companyId, applicationId);
|
||||
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
|
||||
.findByUserIdAndUserWithCompanyIdAndStatus(userEntity.getId(), userWithCompanyEntity.getId(),
|
||||
.findByUserIdAndUserWithCompanyIdAndStatus(userWithCompanyEntity.getUserId(), userWithCompanyEntity.getId(),
|
||||
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
|
||||
companyDao.getUserWithCompany(userEntity.getId(), companyId);
|
||||
if(userCompanyDelegationEntity == null) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.DELEGATION_NOT_FOUND));
|
||||
@@ -270,6 +278,27 @@ public class DelegationDao {
|
||||
return convertUserCompanyDelegationToCompanyDelegationResponse(userCompanyDelegationEntity);
|
||||
}
|
||||
|
||||
private UserWithCompanyEntity validateUserAndGetUserWithCompany(HttpServletRequest request, Long companyId,
|
||||
Long applicationId) {
|
||||
Long userId = null;
|
||||
if (companyId == null && applicationId == null) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST,
|
||||
Translator.toLocale(GepafinConstant.ATLEAST_ONE_ID_REQUIRED));
|
||||
}
|
||||
if (applicationId != null) {
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationId);
|
||||
userId = application.getUserId();
|
||||
companyId = application.getCompanyId();
|
||||
}
|
||||
if (validator.checkIsPreInstructor()) {
|
||||
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluationByApplicationId(applicationId);
|
||||
validator.validatePreInstructor(request, applicationEvaluationEntity.getUserId());
|
||||
} else if (validator.checkIsBeneficiary()) {
|
||||
userId = validator.validateUser(request).getId();
|
||||
}
|
||||
return companyService.getUserWithCompany(userId, companyId);
|
||||
}
|
||||
|
||||
public void deleteCompanyDelegation(UserEntity userEntity, Long companyId) {
|
||||
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyId);
|
||||
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
|
||||
|
||||
@@ -6,6 +6,7 @@ import java.util.stream.Collectors;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.enums.*;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
@@ -54,7 +55,7 @@ public class DocumentDao {
|
||||
private S3PathConfig s3ConfigBean;
|
||||
|
||||
@Autowired
|
||||
private ApplicationRepository applicationFormRepository;
|
||||
private ApplicationRepository applicationRepository;
|
||||
|
||||
@Autowired
|
||||
ApplicationService applicationService;
|
||||
@@ -65,6 +66,9 @@ public class DocumentDao {
|
||||
@Autowired
|
||||
ApplicationAmendmentRequestRepository applicationAmendmentRequestRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
@Value("${aws.s3.bucket.name}")
|
||||
private String bucketName;
|
||||
|
||||
@@ -77,7 +81,7 @@ public class DocumentDao {
|
||||
// @Value("${aws.s3.url.folder}")
|
||||
// private String s3Folder;
|
||||
|
||||
public List<DocumentResponseBean> uploadFiles(List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
|
||||
public List<DocumentResponseBean> uploadFiles(Long userId,List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
|
||||
|
||||
List<DocumentEntity> documentEntities = new ArrayList<>();
|
||||
Long source = resolveSourceId(sourceId, sourceType);
|
||||
@@ -91,6 +95,7 @@ public class DocumentDao {
|
||||
documentEntity.setType(fileType.getValue());
|
||||
documentEntity.setFilePath(uploadFileOnAmazonS3Response.getFilePath());
|
||||
documentEntity.setIsDeleted(false);
|
||||
documentEntity.setUploadedBy(userId);
|
||||
documentEntities.add(documentEntity);
|
||||
}
|
||||
}
|
||||
@@ -116,6 +121,14 @@ public class DocumentDao {
|
||||
userActionContext = UserActionContextEnum.UPLOAD_APPLICATION_DOCUMENT;
|
||||
} else if (fileType.equals(DocumentTypeEnum.IMAGES) && sourceType.equals(DocumentSourceTypeEnum.APPLICATION)) {
|
||||
userActionContext = UserActionContextEnum.UPLOAD_APPLICATION_IMAGES;
|
||||
}else if (fileType.equals(DocumentTypeEnum.DOCUMENT) && sourceType.equals(DocumentSourceTypeEnum.AMENDMENT)) {
|
||||
userActionContext = UserActionContextEnum.UPLOAD_AMENDMENT_DOCUMENT;
|
||||
} else if (fileType.equals(DocumentTypeEnum.IMAGES) && sourceType.equals(DocumentSourceTypeEnum.AMENDMENT)) {
|
||||
userActionContext = UserActionContextEnum.UPLOAD_AMENDMENT_IMAGES;
|
||||
}else if (fileType.equals(DocumentTypeEnum.DOCUMENT) && sourceType.equals(DocumentSourceTypeEnum.EVALUATION)) {
|
||||
userActionContext = UserActionContextEnum.UPLOAD_EVALUATION_DOCUMENT;
|
||||
} else if (fileType.equals(DocumentTypeEnum.IMAGES) && sourceType.equals(DocumentSourceTypeEnum.EVALUATION)) {
|
||||
userActionContext = UserActionContextEnum.UPLOAD_EVALUATION_IMAGES;
|
||||
}
|
||||
|
||||
return userActionContext;
|
||||
@@ -137,15 +150,21 @@ public class DocumentDao {
|
||||
|
||||
Long applicationId = 0L;
|
||||
Long amendmentId = 0L;
|
||||
Long evaluationId = 0L;
|
||||
Long callId = sourceId;
|
||||
if (type == DocumentSourceTypeEnum.APPLICATION) {
|
||||
applicationId = sourceId;
|
||||
callId = applicationFormRepository.findCallIdById(applicationId);
|
||||
callId = applicationRepository.findCallIdById(applicationId);
|
||||
} else if (type == DocumentSourceTypeEnum.AMENDMENT) {
|
||||
amendmentId = sourceId;
|
||||
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
}else if (type == DocumentSourceTypeEnum.EVALUATION) {
|
||||
evaluationId = sourceId;
|
||||
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
}
|
||||
try {
|
||||
String s3Path = generateS3Path(type, callId, applicationId, amendmentId);
|
||||
@@ -188,6 +207,7 @@ public class DocumentDao {
|
||||
Long callId = null;
|
||||
Long applicationId = null;
|
||||
Long amendmentId = null;
|
||||
Long evaluationId = null;
|
||||
|
||||
if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(documentEntity.getSource())) {
|
||||
callId = documentEntity.getSourceId();
|
||||
@@ -201,8 +221,12 @@ public class DocumentDao {
|
||||
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
} else if(DocumentSourceTypeEnum.EVALUATION.getValue().equalsIgnoreCase(documentEntity.getSource())){
|
||||
evaluationId = documentEntity.getSourceId();
|
||||
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
}
|
||||
|
||||
deleteFileFromS3(documentEntity, callId, applicationId,amendmentId);
|
||||
|
||||
}
|
||||
@@ -241,8 +265,9 @@ public class DocumentDao {
|
||||
Long callId=null;
|
||||
Long applicationId=null;
|
||||
Long amendmentId=null;
|
||||
Long evaluationId=null;
|
||||
if (type.equals(DocumentSourceTypeEnum.APPLICATION)) {
|
||||
callId = applicationFormRepository.findCallIdById(id);
|
||||
callId = applicationRepository.findCallIdById(id);
|
||||
applicationId = id;
|
||||
}
|
||||
else if(type.equals(DocumentSourceTypeEnum.AMENDMENT)){
|
||||
@@ -250,7 +275,13 @@ public class DocumentDao {
|
||||
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
}else if(type.equals(DocumentSourceTypeEnum.EVALUATION)){
|
||||
evaluationId = id;
|
||||
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
}
|
||||
|
||||
else {
|
||||
callId = id;
|
||||
applicationId = 0L;
|
||||
|
||||
@@ -8,6 +8,7 @@ import net.gepafin.tendermanagement.enums.RecipientTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.EmailConfig;
|
||||
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AmendmentFormFieldResponse;
|
||||
import net.gepafin.tendermanagement.model.response.EmailContentResponse;
|
||||
import net.gepafin.tendermanagement.model.response.SystemEmailTemplateResponse;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
import net.gepafin.tendermanagement.service.*;
|
||||
@@ -61,9 +62,6 @@ public class EmailNotificationDao {
|
||||
@Autowired
|
||||
private ApplicationFormRepository applicationFormRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationFormFieldRepository applicationFormFieldRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
@@ -77,7 +75,19 @@ public class EmailNotificationDao {
|
||||
// String service = determineService(applicationEntity.getHubId());
|
||||
// String legalMail = service.equals("Gepafin S.p.a.") ? "bandi.gepafin@legalmail.it" : "bandi.sviluppumbria@legalmail.it";
|
||||
|
||||
EmailContentResponse emailContent = prepareEmailContent(applicationEntity, templateType, hubEntity, bodyPlaceholders);
|
||||
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
|
||||
sendEmails(applicationEntity, userEntity, additionalRecipients,amendmentId,emailContent.getSystemEmailTemplateResponse(),emailContent.getSubject(),emailContent.getBody());
|
||||
}
|
||||
|
||||
public EmailContentResponse prepareEmailContent(
|
||||
ApplicationEntity applicationEntity,
|
||||
SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum templateType,
|
||||
HubEntity hubEntity,
|
||||
Map<String, String> bodyPlaceholders
|
||||
) {
|
||||
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService.retrieveTemplateByTypeAndCall(templateType, hubEntity, null);
|
||||
|
||||
Map<String, String> subjectPlaceholders = new HashMap<>();
|
||||
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
|
||||
subjectPlaceholders.put("{{call_name}}", applicationEntity.getCall().getName());
|
||||
@@ -85,9 +95,10 @@ public class EmailNotificationDao {
|
||||
// bodyPlaceholders.put("{{legal_mail}}", legalMail);
|
||||
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
|
||||
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
|
||||
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
|
||||
sendEmails(applicationEntity, userEntity, additionalRecipients,amendmentId,systemEmailTemplateResponse,subject,body);
|
||||
|
||||
return new EmailContentResponse(subject, body, systemEmailTemplateResponse);
|
||||
}
|
||||
|
||||
private void sendEmails(ApplicationEntity applicationEntity, UserEntity userEntity, List<String> additionalRecipients,Long amendmentId,SystemEmailTemplateResponse systemEmailTemplateResponse,String subject,String body) {
|
||||
|
||||
Optional<ApplicationEvaluationEntity> applicationEvaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId());
|
||||
@@ -150,11 +161,16 @@ public class EmailNotificationDao {
|
||||
public void sendMailToNotifyBeneficiaryRegardingNewAmendment(ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity) {
|
||||
|
||||
ApplicationEntity applicationEntity = applicationService.validateApplication(applicationAmendmentRequestEntity.getApplicationId());
|
||||
Map<String, String> bodyPlaceholders = prepareEmailPlaceholders(applicationEntity, applicationAmendmentRequestEntity);
|
||||
sendEmail(applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.DOCUMENTATION_INTEGRATION_REQUEST, bodyPlaceholders, null,
|
||||
applicationAmendmentRequestEntity.getId());
|
||||
}
|
||||
public Map<String, String> prepareEmailPlaceholders(ApplicationEntity applicationEntity, ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity){
|
||||
Map<String, String> bodyPlaceholders = new HashMap<>();
|
||||
bodyPlaceholders.put("{{call_name}}", applicationEntity.getCall().getName());
|
||||
bodyPlaceholders.put("{{protocol_number}}", applicationAmendmentRequestEntity.getProtocol().getProtocolNumber().toString());
|
||||
bodyPlaceholders.put("{{protocol_date}}", DateTimeUtil.formatLocalDateTime(applicationAmendmentRequestEntity.getProtocol().getCreatedDate(), GepafinConstant.DD_MM_YYYY));
|
||||
bodyPlaceholders.put("{{protocol_time}}", DateTimeUtil.parseLocalTimeToString(applicationAmendmentRequestEntity.getProtocol().getTime(), GepafinConstant.HH_MM_SS));
|
||||
bodyPlaceholders.put("{{protocol_number}}", applicationEntity.getProtocol().getProtocolNumber().toString());
|
||||
bodyPlaceholders.put("{{protocol_date}}", DateTimeUtil.formatLocalDateTime(applicationEntity.getProtocol().getCreatedDate(), GepafinConstant.DD_MM_YYYY));
|
||||
bodyPlaceholders.put("{{protocol_time}}", DateTimeUtil.parseLocalTimeToString(applicationEntity.getProtocol().getTime(), GepafinConstant.HH_MM_SS));
|
||||
bodyPlaceholders.put("{{response_days}}", applicationAmendmentRequestEntity.getResponseDays().toString());
|
||||
|
||||
try {
|
||||
@@ -185,8 +201,7 @@ public class EmailNotificationDao {
|
||||
|
||||
|
||||
bodyPlaceholders.put("{{note}}", applicationAmendmentRequestEntity.getNote());
|
||||
sendEmail(applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.DOCUMENTATION_INTEGRATION_REQUEST, bodyPlaceholders, null,
|
||||
applicationAmendmentRequestEntity.getId());
|
||||
return bodyPlaceholders;
|
||||
}
|
||||
|
||||
public List<AmendmentFormFieldResponse> getIdAndLabelFromResult(List<Map<String, Object>> result) {
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import net.gepafin.tendermanagement.entities.NotificationEntity;
|
||||
import net.gepafin.tendermanagement.entities.NotificationTypeEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
|
||||
import net.gepafin.tendermanagement.enums.NotificationEnum;
|
||||
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.model.request.NotificationReq;
|
||||
import net.gepafin.tendermanagement.model.response.NotificationResponse;
|
||||
import net.gepafin.tendermanagement.repositories.NotificationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.NotificationTypeRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserWithCompanyRepository;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hibernate.internal.util.collections.CollectionHelper.listOf;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class NotificationDao {
|
||||
|
||||
@Autowired
|
||||
private SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
@Autowired
|
||||
private NotificationRepository notificationRepository;
|
||||
|
||||
@Autowired
|
||||
private NotificationTypeRepository notificationTypeRepository;
|
||||
|
||||
@Autowired
|
||||
private UserWithCompanyRepository userWithCompanyRepository;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private CompanyDao companyDao;
|
||||
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
|
||||
@Autowired
|
||||
private UserDao userDao;
|
||||
|
||||
public NotificationResponse sendNotification(NotificationReq notificationReq) {
|
||||
|
||||
// Ensure userId is properly set in notificationReq if not already
|
||||
Long userId = notificationReq.getUserId();
|
||||
if (userId == null) {
|
||||
log.error("User ID is missing in the notification request.");
|
||||
return null;
|
||||
}
|
||||
NotificationEntity notificationEntity = saveNotification(notificationReq);
|
||||
log.info("Sending notification to user {} with content: {}", userId, notificationReq.getMessage());
|
||||
List<Long> companyIds = notificationReq.getCompanyIds();
|
||||
|
||||
if (companyIds == null || companyIds.isEmpty()) {
|
||||
sendToUser(userId, notificationEntity);
|
||||
} else {
|
||||
sendToCompanies(userId, companyIds, notificationEntity);
|
||||
}
|
||||
|
||||
return convertNotificationEntityToNotificationResponse(notificationEntity);
|
||||
}
|
||||
|
||||
private NotificationEntity saveNotification(NotificationReq notificationReq) {
|
||||
|
||||
return notificationRepository.save(convertNotificationRequestToNotificationEntity(notificationReq));
|
||||
}
|
||||
|
||||
private void sendToUser(Long userId, NotificationEntity notificationEntity) {
|
||||
|
||||
String userChannel = GepafinConstant.COMMON_SINGLE_CHANNEL_PREFIX + userId;
|
||||
log.info("Channel for User {}", userChannel);
|
||||
NotificationResponse notificationResponse = convertNotificationEntityToNotificationResponse(notificationEntity);
|
||||
messagingTemplate.convertAndSend(userChannel, notificationResponse);
|
||||
}
|
||||
|
||||
private void sendToCompanies(Long userId, List<Long> companyIds, NotificationEntity notificationEntity) {
|
||||
// Send notification to each company provided in the companyIds list
|
||||
companyIds.forEach(companyId -> {
|
||||
UserWithCompanyEntity userWithCompany = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalseForNotification(userId, companyId);
|
||||
String companyChannel = Utils.createChannelForUserAndCompany(userId, companyId);
|
||||
log.info("Channel for User and Company {}, {}", userId, companyChannel);
|
||||
if (userWithCompany == null) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, GepafinConstant.USER_WITH_COMPANY_NOT_FOUND);
|
||||
}
|
||||
notificationEntity.setUserWithCompany(userWithCompany);
|
||||
notificationRepository.save(notificationEntity);
|
||||
NotificationResponse notificationResponse = convertNotificationEntityToNotificationResponse(notificationEntity);
|
||||
messagingTemplate.convertAndSend(companyChannel, notificationResponse);
|
||||
});
|
||||
}
|
||||
|
||||
private NotificationResponse convertNotificationEntityToNotificationResponse(NotificationEntity notificationEntity) {
|
||||
|
||||
NotificationResponse notificationResponse = new NotificationResponse();
|
||||
notificationResponse.setId(notificationEntity.getId());
|
||||
notificationResponse.setUserId(notificationEntity.getUserId());
|
||||
notificationResponse.setStatus(notificationEntity.getStatus());
|
||||
notificationResponse.setMessage(notificationEntity.getMessage());
|
||||
notificationResponse.setCreatedDate(notificationEntity.getCreatedDate());
|
||||
notificationResponse.setUpdatedDate(notificationEntity.getUpdatedDate());
|
||||
notificationResponse.setRedirectUrl(notificationEntity.getNotificationType());
|
||||
notificationResponse.setCompanyId(notificationEntity.getUserWithCompany() != null ? notificationEntity.getUserWithCompany().getCompanyId() : null);
|
||||
notificationResponse.setNotificationType(notificationEntity.getNotificationType());
|
||||
notificationResponse.setTitle(notificationEntity.getTitle());
|
||||
return notificationResponse;
|
||||
}
|
||||
|
||||
private NotificationEntity convertNotificationRequestToNotificationEntity(NotificationReq notificationReq) {
|
||||
|
||||
NotificationEntity notificationEntity = new NotificationEntity();
|
||||
String message = notificationReq.getMessage();
|
||||
notificationEntity.setNotificationType(notificationReq.getNotificationType());
|
||||
notificationEntity.setUserId(notificationReq.getUserId());
|
||||
notificationEntity.setStatus(NotificationEnum.UNREAD.getValue());
|
||||
notificationEntity.setIsDeleted(Boolean.FALSE);
|
||||
notificationEntity.setUserWithCompany(notificationReq.getUserWithCompanyEntity() != null ? notificationReq.getUserWithCompanyEntity() : null);
|
||||
notificationEntity.setMessage(message);
|
||||
notificationEntity.setTitle(notificationReq.getTitle());
|
||||
return notificationEntity;
|
||||
}
|
||||
|
||||
public NotificationReq createNotificationReq(String notificationType, Map<String, String> placeholders, Long userId, UserWithCompanyEntity userWithCompanyEntity,
|
||||
List<Long> companyIds) {
|
||||
// Create NotificationReq object
|
||||
NotificationReq notificationReq = new NotificationReq();
|
||||
NotificationTypeEntity notificationTypeEntity = notificationTypeRepository.findByNotificationNameAndIsDeletedFalse(notificationType);
|
||||
notificationReq.setNotificationType(notificationType);
|
||||
String message = Utils.replacePlaceholders(notificationTypeEntity.getJsonTemplate(), placeholders);
|
||||
notificationReq.setMessage(message);
|
||||
notificationReq.setUserId(userId);
|
||||
notificationReq.setCompanyIds(companyIds);
|
||||
String title = Utils.replacePlaceholders(notificationTypeEntity.getTitle(), placeholders);
|
||||
notificationReq.setTitle(title);
|
||||
notificationReq.setUserWithCompanyEntity(userWithCompanyEntity);
|
||||
return notificationReq;
|
||||
}
|
||||
|
||||
public Map<String, String> sendNotificationToBeneficiary(ApplicationEntity application, NotificationTypeEnum notificationTypeEnum) {
|
||||
|
||||
Map<String, String> placeHolders = new HashMap<>();
|
||||
placeHolders.put("{{call_name}}", application.getCall().getName());
|
||||
placeHolders.put("{{protocol_number}}", String.valueOf(application.getProtocol().getProtocolNumber()));
|
||||
NotificationReq notificationReq = createNotificationReq(notificationTypeEnum.getValue(), placeHolders, application.getUserId(), application.getUserWithCompany(),
|
||||
listOf(application.getCompanyId()));
|
||||
sendNotification(notificationReq);
|
||||
return placeHolders;
|
||||
}
|
||||
|
||||
public void sendNotificationToInstructor(Map<String, String> placeHolders, ApplicationEvaluationEntity applicationEvaluationEntity, NotificationTypeEnum notificationTypeEnum) {
|
||||
|
||||
Long instructorId = applicationEvaluationEntity.getUserId();
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationEvaluationEntity.getApplicationId());
|
||||
if (instructorId != null) {
|
||||
NotificationReq notificationreq = createNotificationReq(notificationTypeEnum.getValue(), placeHolders, instructorId, application.getUserWithCompany(),
|
||||
null);
|
||||
sendNotification(notificationreq);
|
||||
}
|
||||
}
|
||||
public void sendNotificationToSuperUser(ApplicationEntity application, Map<String, String> placeHolders, NotificationTypeEnum notificationTypeEnum) {
|
||||
|
||||
List<UserEntity> user = userRepository.findByRoleEntity_RoleTypeAndHubId(RoleStatusEnum.ROLE_SUPER_ADMIN.getValue(), application.getHubId());
|
||||
UserEntity userEntity1 = user.get(0);
|
||||
if (userEntity1 != null) {
|
||||
NotificationReq notificationreq = createNotificationReq(notificationTypeEnum.getValue(), placeHolders, userEntity1.getId(), application.getUserWithCompany(),
|
||||
null);
|
||||
sendNotification(notificationreq);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Long> getAllCompanyIdsForUser(Long userId) {
|
||||
|
||||
return userWithCompanyRepository.findActiveCompanyIdsByUserId(userId);
|
||||
}
|
||||
|
||||
public NotificationResponse getNotificationById(Long id) {
|
||||
|
||||
NotificationEntity notificationEntity = validateNotificationEntity(id);
|
||||
return convertNotificationEntityToNotificationResponse(notificationEntity);
|
||||
}
|
||||
|
||||
private NotificationEntity validateNotificationEntity(Long id) {
|
||||
|
||||
NotificationEntity notificationEntity = notificationRepository.findByIdAndIsDeletedFalse(id);
|
||||
if (notificationEntity == null) {
|
||||
throw new CustomValidationException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.NOTIFICATION_NOT_FOUND));
|
||||
}
|
||||
return notificationEntity;
|
||||
}
|
||||
|
||||
public List<NotificationResponse> getNotificationByUserId(Long userId, Long companyId, List<NotificationEnum> statuses) {
|
||||
|
||||
List<NotificationEntity> notificationEntities = notificationRepository.findByUserIdAndIsDeletedFalse(userId);
|
||||
UserWithCompanyEntity userWithCompany = null;
|
||||
List<String> statusStrings = new ArrayList<>();
|
||||
if (companyId != null) {
|
||||
userWithCompany = companyDao.validateUserWithCompny(userId, companyId);
|
||||
}
|
||||
|
||||
if (statuses != null) {
|
||||
statusStrings = statuses.stream().map(NotificationEnum::name) // Convert enum to its name as String
|
||||
.toList();
|
||||
notificationEntities = notificationRepository.findByUserIdAndIsDeletedFalseAndStatusIn(userId, statusStrings);
|
||||
|
||||
if (userWithCompany != null) {
|
||||
notificationEntities = notificationRepository.findByUserIdAndUserWithCompanyIdAndIsDeletedFalseAndStatusIn(userId, userWithCompany.getId(), statusStrings);
|
||||
}
|
||||
}
|
||||
|
||||
return notificationEntities.stream().map(this::convertNotificationEntityToNotificationResponse).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public NotificationResponse updateNotificationStatus(Long id, NotificationEnum status) {
|
||||
|
||||
NotificationEntity notificationEntity = validateNotificationEntity(id);
|
||||
if (notificationEntity.getStatus().equals(status.getValue())) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.NOTIFICATION_ALREADY_IN_THAT_STATE));
|
||||
}
|
||||
notificationEntity.setStatus(status.getValue());
|
||||
notificationEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
notificationRepository.save(notificationEntity);
|
||||
return convertNotificationEntityToNotificationResponse(notificationEntity);
|
||||
}
|
||||
|
||||
public void deleteNotification(Long id) {
|
||||
|
||||
NotificationEntity notificationEntity = validateNotificationEntity(id);
|
||||
notificationEntity.setIsDeleted(true);
|
||||
notificationRepository.save(notificationEntity);
|
||||
}
|
||||
|
||||
public List<NotificationResponse> getNotificationByCompanyIdAndUserId(Long userId, Long companyId, List<NotificationEnum> statuses) {
|
||||
|
||||
List<NotificationEntity> notificationEntities = notificationRepository.findByUserIdAndIsDeletedFalse(userId);
|
||||
UserWithCompanyEntity userWithCompany = null;
|
||||
List<String> statusStrings;
|
||||
if (companyId != null) {
|
||||
userWithCompany = companyDao.validateUserWithCompny(userId, companyId);
|
||||
}
|
||||
|
||||
if (statuses != null) {
|
||||
statusStrings = statuses.stream().map(NotificationEnum::name)
|
||||
.toList();
|
||||
notificationEntities = notificationRepository.findByUserIdAndIsDeletedFalseAndStatusIn(userId, statusStrings);
|
||||
|
||||
if (userWithCompany != null) {
|
||||
notificationEntities = notificationRepository.findByUserIdAndUserWithCompanyIdAndIsDeletedFalseAndStatusIn(userId, userWithCompany.getId(), statusStrings);
|
||||
}
|
||||
}
|
||||
|
||||
return notificationEntities.stream().map(this::convertNotificationEntityToNotificationResponse).toList();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.enums.ProtocolTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
@@ -42,7 +43,7 @@ public class ProtocolDao {
|
||||
return (maxProtocolNumber != null) ? maxProtocolNumber + 1 : startNumber;
|
||||
}
|
||||
|
||||
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Long protocolNumber, Long hubId){
|
||||
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Long protocolNumber, Long hubId,Boolean isForApplication){
|
||||
ProtocolEntity protocolEntity=new ProtocolEntity();
|
||||
protocolEntity.setCall(applicationEntity.getCall().getId());
|
||||
LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
|
||||
@@ -51,6 +52,11 @@ public class ProtocolDao {
|
||||
protocolEntity.setTime(LocalTime.now());
|
||||
protocolEntity.setApplicationId(applicationEntity.getId());
|
||||
protocolEntity.setHubId(hubId);
|
||||
if(Boolean.TRUE.equals(isForApplication)){
|
||||
protocolEntity.setType(ProtocolTypeEnum.INPUT.getValue());
|
||||
}else {
|
||||
protocolEntity.setType(ProtocolTypeEnum.OUTPUT.getValue());
|
||||
}
|
||||
protocolRepository.save(protocolEntity);
|
||||
|
||||
/** This code is responsible for adding a version history log for "create protocol" operation. **/
|
||||
|
||||
@@ -448,12 +448,14 @@ public class UserDao {
|
||||
return authService.validateNewUserToken(token);
|
||||
}
|
||||
|
||||
public List<UserResponseBean> getAllUsers(UserEntity user, Long roleId) {
|
||||
public List<UserResponseBean> getAllUsers(UserEntity user, List<Long> roleIds) {
|
||||
List<UserEntity> users;
|
||||
if (roleId != null) {
|
||||
log.info("Fetching users by role ID: {}", roleId);
|
||||
RoleEntity roleEntity=roleService.validateRole(roleId);
|
||||
users = userRepository.findByRoleEntityIdAndHubId(roleEntity.getId(), user.getHub().getId());
|
||||
if (roleIds != null) {
|
||||
log.info("Fetching users by role ID: {}", roleIds);
|
||||
List<RoleEntity> roleEntities = roleIds.stream()
|
||||
.map(roleService::validateRole) // Assuming `validateRole` takes an ID and returns a RoleEntity
|
||||
.collect(Collectors.toList());
|
||||
users = userRepository.findByRoleEntityIdInAndHubId(roleIds, user.getHub().getId());
|
||||
} else {
|
||||
log.info("Fetching all users");
|
||||
users = userRepository.findByHubId(user.getHub().getId());
|
||||
@@ -462,7 +464,7 @@ public class UserDao {
|
||||
.map(this::convertUserEntityToUserResponse)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
log.info("Total users found with role ID {}: {}", roleId, userResponseBeans.size());
|
||||
log.info("Total users found with role ID {}: {}", roleIds, userResponseBeans.size());
|
||||
return userResponseBeans;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user