Resolved conflicts
This commit is contained in:
@@ -23,8 +23,7 @@ public class TendermanagementApplication {
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedOrigins("http://localhost:3000")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD").allowCredentials(true);
|
||||
registry.addMapping("/**").allowedOrigins("http://localhost:3000").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD").allowCredentials(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,7 @@ public class SecurityConfig {
|
||||
.requestMatchers("/v1/api-docs/**").permitAll() // API docs
|
||||
.requestMatchers("/v1/user/reset-password/initiate").permitAll()
|
||||
.requestMatchers("/v1/user/reset-password").permitAll()
|
||||
.requestMatchers("/wss/**").permitAll() // if this is not running use this /gs-guide-websocket
|
||||
.anyRequest().authenticated())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
|
||||
.exceptionHandling(exceptionHandling -> exceptionHandling
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package net.gepafin.tendermanagement.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Value("${spring.rabbitmq.host}")
|
||||
private String relayHost;
|
||||
|
||||
@Value("${spring.rabbitmq.port}")
|
||||
private int relayPort;
|
||||
|
||||
@Value("${spring.rabbitmq.username}")
|
||||
private String clientUserName;
|
||||
|
||||
@Value("${spring.rabbitmq.password}")
|
||||
private String clientPassword;
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||
|
||||
config.enableStompBrokerRelay("/topic").setRelayHost(relayHost).setRelayPort(relayPort).setClientLogin(clientUserName).setClientPasscode(clientPassword);
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
|
||||
registry.addEndpoint("/wss").setAllowedOrigins("http://localhost:3000", "http://127.0.0.1:5500/", "https://bandi-staging.memento.credit/**", "https://bandi.gepafin.it/**")
|
||||
.withSockJS();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package net.gepafin.tendermanagement.constants;
|
||||
|
||||
public class AppointmentApiConstant {
|
||||
|
||||
public static final String ODESSA_LOGIN = "/WSGatewayLogin.apiLogin";
|
||||
public static final String GET_NDG_BY_VAT_NUMBER = "/WSAnagrafica.getListaNdg";
|
||||
public static final String CREATE_VISURA = "/WSAnagrafica.createVisura";
|
||||
public static final String GET_VISURA_LIST = "/WSAnagrafica.getVisuraList";
|
||||
public static final String GET_APPOINTMENT_TEMPLATE = "/WSCrmConsulenza.getAppuntamentoTemplate?idAppuntamentoTemplate=7";
|
||||
public static final String CREATE_APPOINTMENT_FROM_TEMPLATE = "/WSCrmConsulenza.createAppointmentFromTemplate";
|
||||
public static final String UPLOAD_APOOINTMENT_DOCUMENT = "/WSDocumentDetail.createStream";
|
||||
|
||||
//get ndg number
|
||||
public static final int TARGET_PAGE_SIZE = 1;
|
||||
public static final int RECORD_PER_PAGE_SIZE = 10;
|
||||
|
||||
//create visura request Body constant
|
||||
public static final boolean CREA_ANAGRAFICA = Boolean.TRUE;
|
||||
public static final boolean SALVA_DOCUMENTI = Boolean.TRUE;
|
||||
public static final String VISURA_PROVIDER = "cerved";
|
||||
public static final String VISURA_TYPE = "StandardReport";
|
||||
public static final String VISURA_MODE = "visure";
|
||||
public static final String COD_AGENTE = "UtenzaAPIPortal";
|
||||
public static final boolean IS_FROM_RATING = Boolean.FALSE;
|
||||
public static final boolean IS_ANAGRAFICA_LEGAME = Boolean.FALSE;
|
||||
|
||||
}
|
||||
@@ -306,5 +306,53 @@ public class GepafinConstant {
|
||||
public static final String LOGIN_ATTEMPT_ID = "loginAttemptId";
|
||||
public static final String USER_ACTION_ID = "userActionId";
|
||||
public static final String VALID_VATNUMBER_MSG = "valid.vatnumber.message";
|
||||
public static final String ATLEAST_ONE_ID_REQUIRED="atleast.one.id.required";
|
||||
|
||||
//Appointment
|
||||
public static final String NDG_IN_PROGRESS = "IN_PROGRESS";
|
||||
public static final String NDG_AVAILABLE = "ndg.available";
|
||||
public static final String NDG_GENERATION_IS_IN_PROGRESS = "ndg.generation.in.progress";
|
||||
public static final String NDG_GENERATED = "NDG_GENERATED";
|
||||
public static final String NDG_FAILED = "FAILED";
|
||||
public static final String NDG_NOT_FOUND_FOR_APPLICATION = "ndg.not.found.for.this.application.or.invalid";
|
||||
public static final String APPOINTMENT_ALREADY_CREATED = "appointment.already.created";
|
||||
public static final String EXTERNAL_DOCUMENT_UPLOAD_FAILURE_MSG = "document.not.uploaded.to.external.system.please.try.again";
|
||||
public static final String PROVIDE_VALID_APPLICATION_DOC_ID = "provide.valid.application.document.id";
|
||||
public static final String DOCUMENT_UPLOADED_SUCCESSFULLY_TO_EXTERNAL_SYSTEM = "document.uploaded.successfully.to.external.system";
|
||||
public static final String ERROR_UPLOADING_DOCUMENT = "error.in.uploading.document.check.input";
|
||||
public static final String DOCUMENT_ALREADY_UPLOADED = "document.already.uploaded";
|
||||
public static final String NDG_NOT_MATCHED_OR_NOT_FOUND = "ndg.not.found.or.not.matched";
|
||||
public static final String NO_NDG_FOR_ANOTHER_HUB = "ndg.generation.is.only.for.gepafin";
|
||||
public static final String NO_APPOINTMENT_FOR_ANOTHER_HUB = "appointment.creation.is.only.for.gepafin";
|
||||
public static final String NO_DOCUMENT_UPLOAD_FOR_ANOTHER_HUB = "upload.document.is.only.for.gepafin";
|
||||
public static final String APPOINTMENT_CREATED = "appointment.created.successfully";
|
||||
public static final String DATA_STRING = "data";
|
||||
public static final String DOCUMENT_ATTACHMENT_ID_STRING = "documentAttachmentId";
|
||||
public static final String TEMP_FILE_PATH = "/tmp/";
|
||||
public static final String RICHIESTA_CLIENTE_STRING = "richiestaCliente";
|
||||
public static final String ID_STRING = "id";
|
||||
public static final String NULL_STRING = "null";
|
||||
public static final String NDG_STRING = "ndg";
|
||||
public static final String ID_VISURA_STRING = "idVisura";
|
||||
public static final String NDG_FETCH_SUCCESSFULLY = "ndg.fetch.successfully";
|
||||
public static final String AUTH_JWT_SECRET_KEY = "hTa5qe$af/4',BFs";
|
||||
public static final String JWT_ALGO_HEADER = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
|
||||
public static final String HMAC_ALGO = "HmacSHA256";
|
||||
public static final String ERROR_IN_GENERATING_NDG_TRY_AGAIN = "error.try.again";
|
||||
public static final String POLLING_THREAD_NAME = "Ndg-Polling-Thread-";
|
||||
public static final String DOCUMENT_UPLOADING_IN_PROGRESS = "document.uploading.is.in.progress";
|
||||
public static final String ASYNC_DOCUMENT_UPLOAD_NAME = "AsyncDocumentUpload-";
|
||||
public static final String All_DOCUMENT_CHECKED_AND_ONE_CHECKLIST_CHECKED="all.document.checked.and.one.checklist.checked";
|
||||
|
||||
//Notification
|
||||
public static final String COMMON_SINGLE_CHANNEL_PREFIX = "/topic/notifications_user_";
|
||||
public static final String COMPANY_PREFIX = "_company_";
|
||||
public static final String NOTIFICATION_SENT_SUCCESSFULLY = "notification.sent.successfully";
|
||||
public static final String NOTIFICATION_FETCHED_SUCCESSFULLY= "notification.fetched.successfully";
|
||||
public static final String NOTIFICATION_NOT_FOUND= "notification.not.found";
|
||||
public static final String NOTIFICATION_ALREADY_IN_THAT_STATE="notification.already.in.state";
|
||||
public static final String NOTIFICATION_DELETED_SUCCESSFULLY="notification.deleted.successfully";
|
||||
public static final String NOTIFICATION_UPDATED_SUCCESSFULLY="notification.updated.successfully";
|
||||
public static final String USER_WITH_COMPANY_NOT_FOUND = "user.with.company.not.found";
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -50,4 +50,7 @@ public class ApplicationAmendmentRequestEntity extends BaseEntity {
|
||||
@Column(name = "end_date")
|
||||
private LocalDateTime endDate;
|
||||
|
||||
@Column(name = "amendment_document")
|
||||
private String amendmentDocument;
|
||||
|
||||
}
|
||||
|
||||
@@ -42,4 +42,17 @@ public class ApplicationEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "USER_WITH_COMPANY_ID")
|
||||
private UserWithCompanyEntity userWithCompany;
|
||||
|
||||
@Column(name = "NDG")
|
||||
private String ndg;
|
||||
|
||||
@Column(name = "ID_VISURA")
|
||||
private String idVisura;
|
||||
|
||||
@Column(name = "NDG_STATUS")
|
||||
private String ndgStatus;
|
||||
|
||||
@Column(name = "APPOINTMENT_ID")
|
||||
private String appointmentId;
|
||||
|
||||
}
|
||||
@@ -22,6 +22,9 @@ public class ApplicationEvaluationEntity extends BaseEntity{
|
||||
@Column(name = "checklist")
|
||||
private String checklist;
|
||||
|
||||
@Column(name = "EVALUATION_DOCUMENT")
|
||||
private String evaluationDocument;
|
||||
|
||||
@Column(name = "file")
|
||||
private String file;
|
||||
|
||||
@@ -58,4 +61,8 @@ public class ApplicationEvaluationEntity extends BaseEntity{
|
||||
|
||||
@Column(name = "STOP_DATE_TIME")
|
||||
private LocalDateTime stopDateTime;
|
||||
|
||||
@Column(name = "CLOSING_DATE")
|
||||
private LocalDateTime closingDate;
|
||||
|
||||
}
|
||||
|
||||
@@ -66,4 +66,6 @@ public class CompanyEntity extends BaseEntity{
|
||||
@Column(name = "JSON")
|
||||
private String json;
|
||||
|
||||
@Column(name = "NDG")
|
||||
private String ndg;
|
||||
}
|
||||
|
||||
@@ -29,4 +29,10 @@ public class DocumentEntity extends BaseEntity{
|
||||
@Column(name ="IS_DELETED", nullable = false)
|
||||
private Boolean isDeleted = false;
|
||||
|
||||
@Column(name="DOCUMENT_ATTACHMENT_ID")
|
||||
private String documentAttachmentId;
|
||||
|
||||
@Column(name="uploaded_by")
|
||||
private Long uploadedBy;
|
||||
|
||||
}
|
||||
|
||||
@@ -54,4 +54,13 @@ public class HubEntity extends BaseEntity{
|
||||
|
||||
@Column(name = "EMAIL_SERVICE_CONFIG")
|
||||
private String emailServiceConfig;
|
||||
|
||||
@Column(name = "AUTH_TOKEN")
|
||||
private String authToken;
|
||||
|
||||
@Column(name = "APPOINTMENT_AUTH_TOKEN_ID")
|
||||
private String appointmentAuthTokenId;
|
||||
|
||||
@Column(name = "AREA_CODE")
|
||||
private String areaCode;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Data;
|
||||
|
||||
@Entity
|
||||
@Table(name = "NOTIFICATION")
|
||||
@Data
|
||||
public class NotificationEntity extends BaseEntity {
|
||||
|
||||
@Column(name = "USER_ID")
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "MESSAGE")
|
||||
private String message;
|
||||
|
||||
@Column(name = "TITLE")
|
||||
private String title;
|
||||
|
||||
@Column(name = "STATUS")
|
||||
private String status;
|
||||
|
||||
@Column(name = "IS_DELETED")
|
||||
private Boolean isDeleted;
|
||||
|
||||
@Column(name = "NOTIFICATION_TYPE")
|
||||
private String notificationType;
|
||||
|
||||
@Column(name = "REDIRECT_LINK")
|
||||
private String redirectLink;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "USER_WITH_COMPANY_ID")
|
||||
private UserWithCompanyEntity userWithCompany;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Data;
|
||||
|
||||
@Entity
|
||||
@Data
|
||||
@Table(name = "NOTIFICATION_TYPE")
|
||||
public class NotificationTypeEntity extends BaseEntity {
|
||||
|
||||
@Column(name = "NOTIFICATION_NAME")
|
||||
private String notificationName;
|
||||
|
||||
@Column(name = "JSON_TEMPLATE")
|
||||
private String jsonTemplate;
|
||||
|
||||
@Column(name = "TITLE")
|
||||
private String title;
|
||||
|
||||
@Column(name="IS_DELETED")
|
||||
private Boolean isDeleted;
|
||||
}
|
||||
@@ -28,4 +28,7 @@ public class ProtocolEntity extends BaseEntity {
|
||||
@Column(name="HUB_ID")
|
||||
private Long hubId;
|
||||
|
||||
@Column(name = "type")
|
||||
private String type;
|
||||
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ public enum ApplicationStatusTypeEnum {
|
||||
SOCCORSO("SOCCORSO"),
|
||||
APPROVED("APPROVED"),
|
||||
REJECTED("REJECTED"),
|
||||
EVALUATION("EVALUATION");
|
||||
EVALUATION("EVALUATION"),
|
||||
APPOINTMENT("APPOINTMENT"),
|
||||
NDG("NDG"),
|
||||
ADMISSIBLE("ADMISSIBLE");
|
||||
|
||||
private String value;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ public enum DocOtherSourceTypeEnum {
|
||||
TEMPLATE("TEMPLATE"),
|
||||
DELETED_USER_DELEGATION("DELETED_USER_DELEGATION"),
|
||||
DELETED_APPLICATION("DELETED_APPLICATION"),
|
||||
DELETED_EVALUATION("DELETED_EVALUATION"),
|
||||
DELETED_CALL("DELETED_CALL"),
|
||||
DELETED_AMENDMENT("DELETED_AMENDMENT");
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ public enum DocumentSourceTypeEnum {
|
||||
CALL("CALL"),
|
||||
|
||||
APPLICATION("APPLICATION"),
|
||||
|
||||
EVALUATION("EVALUATION"),
|
||||
AMENDMENT("AMENDMENT");
|
||||
|
||||
private String value;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package net.gepafin.tendermanagement.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum NotificationEnum {
|
||||
//status
|
||||
READ("READ"), UNREAD("UNREAD");
|
||||
|
||||
private final String value;
|
||||
|
||||
NotificationEnum(String value) {
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.gepafin.tendermanagement.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum NotificationTypeEnum {
|
||||
CALL_CREATED("CALL_CREATED"),
|
||||
APPLICATION_SUBMISSION("APPLICATION_SUBMISSION"),
|
||||
AMENDMENT_CREATION("AMENDMENT_CREATION"),
|
||||
EVALUATION_RESULT("EVALUATION_RESULT"),
|
||||
AMENDMENT_EXPIRED("AMENDMENT_EXPIRED"),
|
||||
AMENDMENT_CLOSED("AMENDMENT_CLOSED"),
|
||||
NDG_GENERATION("NDG_GENERATION"),
|
||||
EVALUATION_CREATION("EVALUATION_CREATION"),
|
||||
EVALUATION_EXPIRED("EVALUATION_EXPIRED");
|
||||
|
||||
private final String value;
|
||||
|
||||
NotificationTypeEnum(String value) {
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.gepafin.tendermanagement.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum ProtocolTypeEnum {
|
||||
INPUT("INPUT"),
|
||||
OUTPUT("OUTPUT");
|
||||
|
||||
private String value;
|
||||
|
||||
ProtocolTypeEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,8 @@ public enum RoleStatusEnum {
|
||||
ROLE_BENEFICIARY("ROLE_BENEFICIARY"),
|
||||
ROLE_SUPER_ADMIN("ROLE_SUPER_ADMIN"),
|
||||
ROLE_PRE_INSTRUCTOR("ROLE_PRE_INSTRUCTOR"),
|
||||
ROLE_GEPAFIN_OPERATOR("ROLE_GEPAFIN_OPERATOR");
|
||||
ROLE_GEPAFIN_OPERATOR("ROLE_GEPAFIN_OPERATOR"),
|
||||
ROLE_INSTRUCTOR_MANAGER("ROLE_INSTRUCTOR_MANAGER");
|
||||
|
||||
private String value;
|
||||
|
||||
|
||||
@@ -118,6 +118,10 @@ public enum UserActionContextEnum {
|
||||
UPDATE_DOCUMENT("UPDATE_DOCUEMENT"),
|
||||
UPDATE_IMAGES("UPDATE_IMAGES"),
|
||||
GET_DOCUMENT("GET_DOCUMENT"),
|
||||
UPLOAD_AMENDMENT_DOCUMENT("UPLOAD_AMENDMENT_DOCUMENT"),
|
||||
UPLOAD_AMENDMENT_IMAGES("UPLOAD_AMENDMENT_IMAGES"),
|
||||
UPLOAD_EVALUATION_DOCUMENT("UPLOAD_EVALUATION_DOCUMENT"),
|
||||
UPLOAD_EVALUATION_IMAGES("UPLOAD_EVALUATION_IMAGES"),
|
||||
|
||||
/** Assigned flow context **/
|
||||
CREATE_UPDATE_FLOW("CREATE_UPDATE_FLOW"),
|
||||
@@ -136,6 +140,7 @@ public enum UserActionContextEnum {
|
||||
UPDATE_EVALUATION_CRITERIA("UPDATE_EVALUATION_CRITERIA"),
|
||||
DELETE_EVALUATION_CRITERIA("DELETE_EVALUATION_CRITERIA"),
|
||||
CREATE_EVALUATION_CRITERIA("CREATE_EVALUATION_CRITERIA"),
|
||||
UPLOAD_EVALUATION_DOC("UPLOAD_EVALUATION_DOC"),
|
||||
|
||||
/** communication action context **/
|
||||
ADD_COMMENT_TO_AMENDMENT_REQUEST("ADD_COMMENT_TO_AMENDMENT_REQUEST"),
|
||||
@@ -151,7 +156,12 @@ public enum UserActionContextEnum {
|
||||
|
||||
/** scheduler action context **/
|
||||
AMENDMENT_EXPIRATION_SCHEDULER("AMENDMENT_EXPIRATION_SCHEDULER"),
|
||||
EVALUATION_EXPIRATION_SCHEDULER("EVALUATION_EXPIRATION_SCHEDULER");
|
||||
EVALUATION_EXPIRATION_SCHEDULER("EVALUATION_EXPIRATION_SCHEDULER"),
|
||||
|
||||
/** appointment action context **/
|
||||
CHECK_OR_CREATE_NDG_CODE("CHECK_OR_CREATE_NDG_CODE"),
|
||||
CREATE_APPOINTMENT("CREATE_APPOINTMENT"),
|
||||
UPLOAD_DOCUMENT_TO_EXTERNAL_SYSTEM("UPLOAD_DOCUMENT_TO_EXTERNAL_SYSTEM");
|
||||
|
||||
private final String value;
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AmendmentDetailsRequest {
|
||||
|
||||
private String fieldId;
|
||||
|
||||
private Long amendmentId;
|
||||
|
||||
private Boolean valid;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AmendmentFieldRequest {
|
||||
|
||||
private String fieldId;
|
||||
private String nameValue;
|
||||
private String fileValue;
|
||||
private Boolean valid = false;
|
||||
|
||||
}
|
||||
@@ -9,9 +9,13 @@ public class AmendmentFormField {
|
||||
|
||||
private String fieldId;
|
||||
|
||||
private String label;
|
||||
|
||||
private String fieldValue;
|
||||
|
||||
private String isUploadedBy;
|
||||
private Boolean valid;
|
||||
|
||||
|
||||
|
||||
|
||||
public enum AmendmentIsUploadedByEnum {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AmendmentFormFieldRequest {
|
||||
|
||||
private String fieldId;
|
||||
|
||||
private Object fieldValue;
|
||||
|
||||
private Boolean valid;
|
||||
}
|
||||
@@ -7,5 +7,7 @@ import lombok.Data;
|
||||
@Data
|
||||
public class ApplicationAmendmentRequestBean {
|
||||
private String note;
|
||||
private List<ApplicationFormFieldRequestBean> applicationFormFields;
|
||||
private List<AmendmentFormFieldRequest> applicationFormFields;
|
||||
private String amendmentDocuments;
|
||||
private String amendmentNotes;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ public class ApplicationEvaluationRequest {
|
||||
private List<CriteriaRequest> criteria;
|
||||
private List<ChecklistRequest> checklist;
|
||||
private List<FieldRequest> files;
|
||||
private List<EvaluationDocumentRequest> evaluationDocument;
|
||||
private List<AmendmentDetailsRequest> amendmentDetails;
|
||||
private String note;
|
||||
private ApplicationStatusForEvaluation applicationStatus;
|
||||
private String motivation;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AppointmentCreationRequest {
|
||||
|
||||
private Input input;
|
||||
|
||||
@Data
|
||||
public static class Input {
|
||||
private String id;
|
||||
private String ndg;
|
||||
private List<RichiestaCliente> richiestaCliente;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class RichiestaCliente {
|
||||
private String codAbi;
|
||||
private String codCab;
|
||||
private Integer durataMesiFinanziamento;
|
||||
private Integer idMotivazione;
|
||||
private String idNota;
|
||||
private String importoAgevolato;
|
||||
private Double importoBreveTermine;
|
||||
private String importoMedioLungoTermine;
|
||||
private String codTipoProdotto;
|
||||
private String codCategoriaProdotto;
|
||||
private String codFormaTecnica;
|
||||
private String codProdotto;
|
||||
private String codOperazione;
|
||||
private Nota nota;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Nota {
|
||||
private String titolo;
|
||||
private String testo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AppointmentNdgRequest {
|
||||
private Filter filter;
|
||||
private Pagination pagination;
|
||||
|
||||
@Data
|
||||
public static class Filter {
|
||||
private String partitaIva;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Pagination {
|
||||
private int targetPage;
|
||||
private int recordsPerPage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AppointmentVisuraListRequest {
|
||||
|
||||
private AppointmentVisuraListRequest.VisuraFilter filter;
|
||||
|
||||
@Data
|
||||
public static class VisuraFilter {
|
||||
private String idVisura;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import lombok.Setter;
|
||||
|
||||
@Data
|
||||
public class AppointmentVisuraRequest {
|
||||
private VisuraInput input;
|
||||
|
||||
@Data
|
||||
public static class VisuraInput {
|
||||
private String codiceFiscale;
|
||||
private String partitaIva;
|
||||
private boolean creaAnagrafica;
|
||||
private boolean salvaDocumenti;
|
||||
private String visuraProvider;
|
||||
private String visuraType;
|
||||
private String visuraMode;
|
||||
private String codArea;
|
||||
private String codAgente;
|
||||
@JsonProperty("isFromRating")
|
||||
private boolean isFromRating;
|
||||
@JsonProperty("isAnagraficaLegame")
|
||||
private boolean isAnagraficaLegame;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CreateAppointmentRequest {
|
||||
private Double importoBreveTermine;
|
||||
private Integer durataMesiFinanziamento;
|
||||
private Nota nota;
|
||||
|
||||
@Data
|
||||
public static class Nota {
|
||||
private String titolo;
|
||||
|
||||
private String testo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class EvaluationDocumentRequest {
|
||||
|
||||
private String fieldId;
|
||||
|
||||
private String nameValue;
|
||||
|
||||
private String fileValue;
|
||||
|
||||
private Boolean valid;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class NotificationReq {
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
Long id;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
Long userId;
|
||||
|
||||
String message;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
String notificationType;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
String status;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private LocalDateTime createdDate;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private LocalDateTime updatedDate;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private String redirectUrl;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private String title;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private List<Long> companyIds;
|
||||
|
||||
@JsonIgnore
|
||||
private UserWithCompanyEntity userWithCompanyEntity;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
|
||||
@Data
|
||||
public class UpdateAssignedApplicationRequest {
|
||||
private String note;
|
||||
private AssignedApplicationEnum status;
|
||||
private Long userId;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UploadDocToExternalSystemRequest {
|
||||
private Input input;
|
||||
|
||||
@Data
|
||||
public static class Input {
|
||||
private Long idTipoProtocollo;
|
||||
private Long idClassificazione;
|
||||
private Boolean flagDaFirmare;
|
||||
private String descrizione;
|
||||
private Attributes attributes;
|
||||
|
||||
@Data
|
||||
public static class Attributes {
|
||||
private String ndg;
|
||||
private String email;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
@Data
|
||||
public class AmendmentDetailsResponseBean {
|
||||
private String amendmentDocuments;
|
||||
private String amendmentNotes;
|
||||
private Boolean valid;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AmendmentDocumentResponseBean {
|
||||
|
||||
private Long amendmentId;
|
||||
private String fieldId;
|
||||
private String label;
|
||||
private Boolean valid;
|
||||
private List<DocumentResponseBean> fileDetail ;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationAmendmentRequestEnum;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
@@ -19,8 +18,12 @@ public class ApplicationAmendmentRequestResponse {
|
||||
private Long protocolNumber;
|
||||
private String callName;
|
||||
private String beneficiaryName;
|
||||
private String companyName;
|
||||
private List<AmendmentFormFieldResponse> formFields;
|
||||
private List<ApplicationFormFieldResponseBean> applicationFormFields;
|
||||
private List<DocumentResponseBean> amendmentDocuments;
|
||||
private String amendmentNotes;
|
||||
private Boolean valid;
|
||||
private Long applicationId;
|
||||
private Long applicationEvaluationId;
|
||||
private LocalDateTime evaluationEndDate;
|
||||
@@ -28,4 +31,5 @@ public class ApplicationAmendmentRequestResponse {
|
||||
private List<CommunicationResponseBean> commentsList;
|
||||
private String internalNote;
|
||||
private ApplicationAmendmentRequestEnum status;
|
||||
private String emailTemplate;
|
||||
}
|
||||
|
||||
@@ -21,13 +21,21 @@ public class ApplicationEvaluationResponse {
|
||||
private List<CriteriaResponse> criteria;
|
||||
private List<ChecklistResponse> checklist;
|
||||
private List<FieldResponse> files;
|
||||
private List<EvaluationDocumentResponse> evaluationDocument;
|
||||
private List<AmendmentDocumentResponseBean> amendmentDetails;
|
||||
private LocalDateTime createdDate;
|
||||
private LocalDateTime updatedDate;
|
||||
private String beneficiary;
|
||||
private Long assignedUserId;
|
||||
private String assignedUserName;
|
||||
private Long protocolNumber;
|
||||
private String callName;
|
||||
private String motivation;
|
||||
private LocalDateTime submissionDate;
|
||||
private LocalDateTime evaluationEndDate;
|
||||
private LocalDateTime callEndDate;
|
||||
private String companyName;
|
||||
private LocalDateTime assignedAt;
|
||||
private String ndg;
|
||||
private String appointmentId;
|
||||
}
|
||||
|
||||
@@ -33,4 +33,8 @@ public class ApplicationResponse{
|
||||
|
||||
private Long protocolNumber;
|
||||
|
||||
private Long assignedUserId;
|
||||
|
||||
private String assignedUserName;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AppointmentCreationResponse {
|
||||
private String appointmentId;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AppointmentLoginResponse {
|
||||
|
||||
private String tokenId;
|
||||
private String areaCode;
|
||||
private Long companyId;
|
||||
private String codecFiscale;
|
||||
private String vatNumber;
|
||||
private String ndg;
|
||||
private String message;
|
||||
private String idVisura;
|
||||
}
|
||||
@@ -25,4 +25,6 @@ public class DocumentResponseBean {
|
||||
private LocalDateTime createdDate;
|
||||
|
||||
private LocalDateTime updatedDate;
|
||||
|
||||
private String documentAttachmentId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class DocumentUploadResponse {
|
||||
private String documentAttachmentId;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class EmailContentResponse {
|
||||
private final String subject;
|
||||
private final String body;
|
||||
private final SystemEmailTemplateResponse systemEmailTemplateResponse;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class EvaluationDocumentResponse {
|
||||
private String fieldId;
|
||||
private String nameValue;
|
||||
private Boolean valid;
|
||||
private List<DocumentResponseBean> fileValue ;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class NdgResponse {
|
||||
private String ndg;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.model.BaseBean;
|
||||
|
||||
@Data
|
||||
public class NotificationResponse extends BaseBean {
|
||||
private Long userId;
|
||||
|
||||
private String title;
|
||||
|
||||
private String message;
|
||||
|
||||
private String status;
|
||||
|
||||
private Long companyId;
|
||||
|
||||
private String redirectUrl;
|
||||
|
||||
private String notificationType;
|
||||
}
|
||||
@@ -40,6 +40,7 @@ public class UserResponseBean extends BaseBean {
|
||||
|
||||
private List<CompanyResponse> companies;
|
||||
private Boolean privacy;
|
||||
|
||||
private Boolean terms;
|
||||
|
||||
private Boolean marketing;
|
||||
|
||||
@@ -44,7 +44,7 @@ public interface ApplicationAmendmentRequestRepository extends JpaRepository<App
|
||||
"FROM ApplicationEntity app " +
|
||||
"WHERE app.id = (SELECT aar.applicationId " +
|
||||
"FROM ApplicationAmendmentRequestEntity aar " +
|
||||
"WHERE aar.id = :amendmentId)")
|
||||
"WHERE aar.id = :amendmentId AND aar.isDeleted = false)")
|
||||
ApplicationEntity findApplicationByAmendmentId(Long amendmentId);
|
||||
|
||||
@Query(value = "SELECT amr " +
|
||||
@@ -52,8 +52,8 @@ public interface ApplicationAmendmentRequestRepository extends JpaRepository<App
|
||||
"WHERE amr.applicationEvaluationEntity.id = :id " +
|
||||
"AND amr.isDeleted = false " +
|
||||
"AND amr.applicationEvaluationEntity.isDeleted = false " +
|
||||
"AND amr.status = :status")
|
||||
List<ApplicationAmendmentRequestEntity> findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(Long id, String status);
|
||||
"AND amr.status IN (:statuses)")
|
||||
List<ApplicationAmendmentRequestEntity> findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(Long id, List<String> statuses);
|
||||
|
||||
@Query("SELECT a FROM ApplicationAmendmentRequestEntity a " +
|
||||
"WHERE a.isDeleted = false " +
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -21,6 +22,12 @@ public interface ApplicationEvaluationRepository extends JpaRepository<Applicati
|
||||
|
||||
Optional<ApplicationEvaluationEntity> findFirstByIsDeletedFalseOrderByCreatedDateDesc();
|
||||
boolean existsByApplicationIdAndIsDeletedFalse(Long applicationId);
|
||||
@Query("SELECT app " +
|
||||
"FROM ApplicationEntity app " +
|
||||
"WHERE app.id = (SELECT aar.applicationId " +
|
||||
"FROM ApplicationEvaluationEntity aar " +
|
||||
"WHERE aar.id = :evaluationId AND aar.isDeleted = false)")
|
||||
ApplicationEntity findApplicationByEvaluationId(Long evaluationId);
|
||||
|
||||
@Query("SELECT a FROM ApplicationEvaluationEntity a WHERE a.isDeleted = false AND a.endDate < :currentDate")
|
||||
List<ApplicationEvaluationEntity> findAllByIsDeletedFalseAndEndDateBefore(@Param("currentDate") LocalDateTime currentDate);
|
||||
|
||||
@@ -42,6 +42,6 @@ public interface ApplicationRepository extends JpaRepository<ApplicationEntity,
|
||||
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'DRAFT' And a.hubId = :hubId AND a.isDeleted = false")
|
||||
public Long countDraftApplicationsByHubId(@Param("hubId") Long hubId);
|
||||
|
||||
@Query("SELECT a.call.id FROM ApplicationEntity a WHERE a.id = :id")
|
||||
@Query("SELECT a.call.id FROM ApplicationEntity a WHERE a.id = :id AND a.isDeleted = false")
|
||||
Long findCallIdById(@Param("id") Long id);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface BeneficiaryRepository extends JpaRepository<BeneficiaryEntity, Long> {
|
||||
|
||||
@Query("SELECT u.id FROM UserEntity u JOIN u.beneficiary b WHERE b.id = u.beneficiary.id AND b.hubId = :hubId")
|
||||
List<Long> findUserIdsByHubIdAndBeneficiaryId(Long hubId);
|
||||
}
|
||||
|
||||
@@ -33,5 +33,7 @@ public interface DocumentRepository extends JpaRepository<DocumentEntity, Long>
|
||||
List<DocumentEntity> findAllByIsDeleteTrue();
|
||||
|
||||
List<DocumentEntity> findAllByIdInAndIsDeletedFalse(Set<Long> documentIds);
|
||||
|
||||
List<DocumentEntity> findBySourceIdInAndSourceAndIsDeletedFalse(Set<Long> sourceId, String type);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface HubRepository extends JpaRepository<HubEntity, Long> {
|
||||
|
||||
Optional<HubEntity> findByUniqueUuid(String hubUuid);
|
||||
|
||||
Optional<HubEntity> findByUniqueUuid(String hubUuid);
|
||||
|
||||
@Query("SELECT h FROM HubEntity h WHERE h.id = :hubId")
|
||||
HubEntity findByHubId(@Param("hubId") Long hubId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.NotificationEntity;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface NotificationRepository extends JpaRepository<NotificationEntity, Long> {
|
||||
|
||||
NotificationEntity findByIdAndIsDeletedFalse(Long id);
|
||||
|
||||
List<NotificationEntity> findByUserIdAndIsDeletedFalse(Long userId);
|
||||
|
||||
List<NotificationEntity> findByUserIdAndUserWithCompanyIdAndIsDeletedFalseAndStatusIn(Long userId, Long userWithCompanyId, List<String> statuses);
|
||||
|
||||
List<NotificationEntity> findByUserIdAndIsDeletedFalseAndStatusIn(Long userId, List<String> statuses);
|
||||
|
||||
List<NotificationEntity> findByUserWithCompanyIdAndUserIdAndIsDeletedFalse(Long userWithCompanyId, Long userId);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.NotificationTypeEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface NotificationTypeRepository extends JpaRepository<NotificationTypeEntity, Long> {
|
||||
NotificationTypeEntity findByNotificationNameAndIsDeletedFalse(String value);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
|
||||
|
||||
boolean existsByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
|
||||
|
||||
List<UserEntity> findByRoleEntityIdAndHubId(Long roleId, Long hubId);
|
||||
List<UserEntity> findByRoleEntityIdInAndHubId(List<Long> roleIds, Long hubId);
|
||||
|
||||
List<UserEntity> findByHubId(Long hubId);
|
||||
|
||||
@@ -25,4 +25,7 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
|
||||
Optional<UserEntity> findByBeneficiaryCodiceFiscaleAndHubId(String codiceFiscale, Long hubId);
|
||||
|
||||
boolean existsByBeneficiaryCodiceFiscaleAndHubId(String codiceFiscale, Long hubId);
|
||||
|
||||
List<UserEntity> findByRoleEntity_RoleTypeAndHubId(String roleType, Long hubId);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserWithCompanyRepository extends JpaRepository<UserWithCompanyEntity, Long> {
|
||||
|
||||
void deleteByCompanyIdAndIsDeletedFalse(Long companyId);
|
||||
void deleteByCompanyIdAndIsDeletedFalse(Long companyId);
|
||||
|
||||
@Query("SELECT u.companyId FROM UserWithCompanyEntity u WHERE u.userId = :userId AND u.isDeleted = false")
|
||||
List<Long> findActiveCompanyIdsByUserId(@Param("userId") Long userId);
|
||||
@Query("SELECT u.companyId FROM UserWithCompanyEntity u WHERE u.userId = :userId AND u.isDeleted = false")
|
||||
List<Long> findActiveCompanyIdsByUserId(@Param("userId") Long userId);
|
||||
|
||||
Optional<UserWithCompanyEntity> findByUserIdAndCompanyIdAndIsDeletedFalse(Long userId, Long companyId);
|
||||
Optional<UserWithCompanyEntity> findByUserIdAndCompanyIdAndIsDeletedFalse(Long userId, Long companyId);
|
||||
|
||||
@Query("SELECT u FROM UserWithCompanyEntity u WHERE u.userId = :userId AND u.companyId = :companyId AND u.isDeleted = false")
|
||||
UserWithCompanyEntity findByUserIdAndCompanyIdAndIsDeletedFalseForNotification(Long userId, Long companyId);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,35 +1,42 @@
|
||||
package net.gepafin.tendermanagement.scheduler;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.ApplicationAmendmentRequestDao;
|
||||
import net.gepafin.tendermanagement.dao.EmailNotificationDao;
|
||||
import net.gepafin.tendermanagement.dao.NotificationDao;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationAmendmentRequestEntity;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationAmendmentRequestEnum;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationEvaluationStatusTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
|
||||
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionContextEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionLogsEnum;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.UserActionRequest;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationAmendmentRequestRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class ApplicationAmendmentScheduler {
|
||||
@@ -40,8 +47,6 @@ public class ApplicationAmendmentScheduler {
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestRepository applicationAmendmentRepository;
|
||||
|
||||
@Autowired
|
||||
private EmailNotificationDao emailNotificationDao;
|
||||
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestDao applicationAmendmentRequestDao;
|
||||
@@ -49,6 +54,21 @@ public class ApplicationAmendmentScheduler {
|
||||
@Autowired
|
||||
private LoggingUtil loggingUtil;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Autowired
|
||||
private AssignedApplicationsRepository assignedApplicationsRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
|
||||
@Autowired
|
||||
private ApplicationRepository applicationRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ApplicationAmendmentScheduler.class);
|
||||
|
||||
@Scheduled(cron = "0 0 1 * * ?")
|
||||
@@ -79,14 +99,16 @@ public class ApplicationAmendmentScheduler {
|
||||
amendmentRequests.forEach(request -> {
|
||||
try {
|
||||
ApplicationAmendmentRequestEntity oldAmendmentRequestEntity = Utils.getClonedEntityForData(request);
|
||||
request.setStatus(ApplicationAmendmentRequestEnum.CLOSE.getValue());
|
||||
request.setStatus(ApplicationAmendmentRequestEnum.EXPIRED.getValue());
|
||||
ApplicationEntity application=oldAmendmentRequestEntity.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication();
|
||||
request = applicationAmendmentRepository.save(request);
|
||||
|
||||
Map<String ,String> placeHolders=notificationDao.sendNotificationToBeneficiary(application,NotificationTypeEnum.AMENDMENT_EXPIRED);
|
||||
notificationDao.sendNotificationToInstructor(placeHolders,oldAmendmentRequestEntity.getApplicationEvaluationEntity(),NotificationTypeEnum.AMENDMENT_EXPIRED);
|
||||
/** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(httpServletRequest).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAmendmentRequestEntity).newData(request).build());
|
||||
|
||||
emailNotificationDao.sendApplicationFailureNotificationEmail(request);
|
||||
log.info("Updated status to CLOSED for ApplicationAmendmentRequest with ID: {}", request.getId());
|
||||
// emailNotificationDao.sendApplicationFailureNotificationEmail(request);
|
||||
log.info("Updated status to EXPIRED for ApplicationAmendmentRequest with ID: {}", request.getId());
|
||||
} catch (Exception e) {
|
||||
log.error("Error expiring ApplicationAmendmentRequest with ID {}: {}", request.getId(), e.getMessage(),
|
||||
e);
|
||||
@@ -104,6 +126,16 @@ public class ApplicationAmendmentScheduler {
|
||||
evaluationsWithoutActiveAmendmentList.forEach(evaluation -> {
|
||||
try {
|
||||
applicationAmendmentRequestDao.calculateEndDateAndSuspensionDays(evaluation);
|
||||
|
||||
updateEvaluationStatus(evaluation);
|
||||
|
||||
// Update AssignedApplicationsEntity status
|
||||
updateAssignedApplicationStatus(evaluation.getAssignedApplicationsEntity());
|
||||
|
||||
// Update ApplicationEntity status
|
||||
updateApplicationStatus(evaluation.getAssignedApplicationsEntity().getApplication());
|
||||
|
||||
|
||||
log.info("Updated EndDate and suspension days for ApplicationEvaluation with ID: {}",
|
||||
evaluation.getId());
|
||||
} catch (Exception e) {
|
||||
@@ -119,4 +151,35 @@ public class ApplicationAmendmentScheduler {
|
||||
|
||||
}
|
||||
|
||||
public void updateAssignedApplicationStatus(AssignedApplicationsEntity assignedApplicationsEntity){
|
||||
AssignedApplicationsEntity oldAssignedApplicationEntity = Utils.getClonedEntityForData(assignedApplicationsEntity);
|
||||
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.OPEN.getValue());
|
||||
assignedApplicationsRepository.save(assignedApplicationsEntity);
|
||||
log.info("Updated status to OPEN for Assigned Application with ID: {}", assignedApplicationsEntity.getId());
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update Assigned Application status" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(httpServletRequest).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplicationEntity).newData(assignedApplicationsEntity).build());
|
||||
|
||||
}
|
||||
|
||||
public void updateApplicationStatus(ApplicationEntity applicationEntity){
|
||||
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(applicationEntity);
|
||||
applicationEntity.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
|
||||
applicationRepository.save(applicationEntity);
|
||||
log.info("Updated status to EVALUATION for Application with ID: {}",applicationEntity.getId());
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update Application Status" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(httpServletRequest).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEntity).newData(applicationEntity).build());
|
||||
|
||||
}
|
||||
public void updateEvaluationStatus(ApplicationEvaluationEntity applicationEvaluationEntity){
|
||||
ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
|
||||
applicationEvaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
|
||||
applicationEvaluationRepository.save(applicationEvaluationEntity);
|
||||
log.info("Updated status to OPEN for ApplicationEvaluation with ID: {}", applicationEvaluationEntity.getId());
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update Application Status" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(httpServletRequest).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluationEntity).newData(applicationEvaluationEntity).build());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package net.gepafin.tendermanagement.scheduler;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.NotificationDao;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationEvaluationStatusTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionContextEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionLogsEnum;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
@@ -22,6 +25,7 @@ import org.springframework.stereotype.Component;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class ApplicationEvaluationScheduler {
|
||||
@@ -35,6 +39,9 @@ public class ApplicationEvaluationScheduler {
|
||||
@Autowired
|
||||
private HttpServletRequest httpServletRequest;
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ApplicationEvaluationScheduler.class);
|
||||
|
||||
@Scheduled(cron = "0 0 2 * * ?") // Runs daily at midnight
|
||||
@@ -76,10 +83,15 @@ public class ApplicationEvaluationScheduler {
|
||||
|
||||
ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils
|
||||
.getClonedEntityForData(evaluation);
|
||||
|
||||
ApplicationEntity application=evaluation.getAssignedApplicationsEntity().getApplication();
|
||||
evaluation.setStatus(ApplicationEvaluationStatusTypeEnum.EXPIRED.getValue());
|
||||
evaluation = applicationEvaluationRepository.save(evaluation);
|
||||
|
||||
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_EXPIRED);
|
||||
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_EXPIRED);
|
||||
notificationDao.sendNotificationToInstructor(placeHolders,evaluation,NotificationTypeEnum.EVALUATION_EXPIRED);
|
||||
|
||||
|
||||
// Logging version history for the update operation
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(httpServletRequest)
|
||||
.actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluationEntity)
|
||||
|
||||
@@ -2,10 +2,12 @@ package net.gepafin.tendermanagement.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationStatusForEvaluation;
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.EvaluationDocumentRequest;
|
||||
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationResponse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ApplicationEvaluationService {
|
||||
ApplicationEvaluationResponse createOrUpdateApplicationEvaluation(
|
||||
HttpServletRequest request,
|
||||
@@ -16,4 +18,7 @@ public interface ApplicationEvaluationService {
|
||||
|
||||
ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(HttpServletRequest request,Long applicationId,Long assignedApplicationId);
|
||||
ApplicationEvaluationEntity validateApplicationEvaluation(Long applicationEvaluationId);
|
||||
|
||||
ApplicationEvaluationEntity validateApplicationEvaluationByApplicationId(Long applicationId);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package net.gepafin.tendermanagement.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.model.request.CreateAppointmentRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UploadDocToExternalSystemRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AppointmentCreationResponse;
|
||||
import net.gepafin.tendermanagement.model.response.DocumentUploadResponse;
|
||||
import net.gepafin.tendermanagement.model.response.NdgResponse;
|
||||
|
||||
public interface AppointmentService {
|
||||
NdgResponse checkNdgForAppointment(HttpServletRequest request, Long applicationId);
|
||||
|
||||
AppointmentCreationResponse createAppointmentForApplication(HttpServletRequest request, Long applicationId, CreateAppointmentRequest createAppointmentRequest);
|
||||
|
||||
DocumentUploadResponse uploadDocToExternalSystem(HttpServletRequest request, Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package net.gepafin.tendermanagement.service;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
|
||||
import java.util.List;
|
||||
@@ -15,7 +16,7 @@ public interface AssignedApplicationsService {
|
||||
void deleteApplication(HttpServletRequest request, Long id);
|
||||
|
||||
List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId);
|
||||
AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, AssignedApplicationsRequest assignedApplicationsRequest);
|
||||
AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, UpdateAssignedApplicationRequest assignedApplicationsRequest);
|
||||
AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id);
|
||||
AssignedApplicationsEntity validateAssignedApplication(Long assignedApplicationId);
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ public interface CompanyService {
|
||||
|
||||
CompanyDelegationResponse uploadCompanyDelegation(HttpServletRequest request, Long companyId, MultipartFile file);
|
||||
|
||||
CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId);
|
||||
CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId,Long applicationId);
|
||||
|
||||
void deleteCompanyDelegation(HttpServletRequest request, Long companyId);
|
||||
UserWithCompanyEntity getUserWithCompanyEntity(Long userId,Long companyId);
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.util.List;
|
||||
|
||||
public interface DocumentService {
|
||||
|
||||
public List<DocumentResponseBean> uploadFile(List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType);
|
||||
public List<DocumentResponseBean> uploadFile(HttpServletRequest request,List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType);
|
||||
|
||||
public void deleteFile(Long documentId);
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package net.gepafin.tendermanagement.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.enums.NotificationEnum;
|
||||
import net.gepafin.tendermanagement.model.request.NotificationReq;
|
||||
import net.gepafin.tendermanagement.model.response.NotificationResponse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface NotificationService {
|
||||
NotificationResponse sendNotification(Long userId, NotificationReq notificationReq, Long companyId);
|
||||
|
||||
public NotificationResponse getNotificationById(HttpServletRequest servletRequest, Long id);
|
||||
|
||||
public List<NotificationResponse> getNotificationByUserId(HttpServletRequest servletRequest, Long userId, Long companyId, List<NotificationEnum> statuses);
|
||||
|
||||
public NotificationResponse updateNotificationStatus(HttpServletRequest request, Long id, NotificationEnum status);
|
||||
|
||||
public void deleteNotification(HttpServletRequest request, Long id);
|
||||
|
||||
public List<NotificationResponse> getNotificationsByCompanyIdAndUserId(Long userId, Long companyId, List<NotificationEnum> statuses);
|
||||
|
||||
}
|
||||
@@ -45,6 +45,6 @@ public interface UserService {
|
||||
UserEntity getUserByBeneficiaryId(Long beneficiaryId);
|
||||
|
||||
public UserEntity getUserEntityById(Long userId);
|
||||
List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId);
|
||||
List<UserResponseBean> getAllUsers(HttpServletRequest request, List<Long> roleIds);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package net.gepafin.tendermanagement.service.feignClient;
|
||||
|
||||
import net.gepafin.tendermanagement.constants.AppointmentApiConstant;
|
||||
import net.gepafin.tendermanagement.model.request.AppointmentNdgRequest;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@FeignClient(value = "appointment-api-service", url = "${appointment.base.url}")
|
||||
public interface AppointmentApiService {
|
||||
|
||||
@PostMapping(value = AppointmentApiConstant.ODESSA_LOGIN, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Object> loginWithOdessa(@RequestHeader("auth") String authToken, @RequestHeader("source") String source, @RequestHeader("context") String context,
|
||||
@RequestHeader("user") String user, @RequestHeader("password") String password, @RequestBody(required = false) Map<String, Object> body);
|
||||
|
||||
@PostMapping(value = AppointmentApiConstant.GET_NDG_BY_VAT_NUMBER, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Object> getNdgByVatNumber(@RequestBody AppointmentNdgRequest ndgRequest, @RequestHeader("Authorization") String token);
|
||||
|
||||
@PostMapping(value = AppointmentApiConstant.CREATE_VISURA, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Object> createVisura(@RequestBody String visuraRequest, @RequestHeader("Authorization") String token);
|
||||
|
||||
@GetMapping(value = AppointmentApiConstant.GET_VISURA_LIST, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Object> getVisuraList(@RequestBody String visuraRequest, @RequestHeader("Authorization") String token);
|
||||
|
||||
@GetMapping(value = AppointmentApiConstant.GET_APPOINTMENT_TEMPLATE, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Object> getAppointmentTemplateForTemplateCreation(@RequestHeader("Authorization") String token);
|
||||
|
||||
@PostMapping(value = AppointmentApiConstant.CREATE_APPOINTMENT_FROM_TEMPLATE, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Object> createAppointment(@RequestHeader("Authorization") String token, @RequestHeader("context") String context, String appointmentCreationRequest);
|
||||
|
||||
@PostMapping(value = AppointmentApiConstant.UPLOAD_APOOINTMENT_DOCUMENT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
ResponseEntity<Object> uploadDocumentToExternalSystemForAppointment(@RequestHeader("Authorization") String token, @RequestHeader("context") String context,
|
||||
@RequestPart("input") String uploadDocumentRequest, @RequestPart("file") MultipartFile file);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -87,9 +90,11 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
|
||||
if(Boolean.FALSE.equals(isTestProfileActivated())) {
|
||||
amazonS3.putObject(bucketName, path, inputStream, objectMetadata);
|
||||
}
|
||||
path =s3Url + s3Folder +"/"+ fileName;
|
||||
log.info("File '{}' uploaded successfully to Amazon S3 with URL: {}", fileName, path);
|
||||
return path;
|
||||
//getting actual encoded s3 file path
|
||||
URL amazonS3Url = amazonS3.getUrl(bucketName, path);
|
||||
String fileUrl = amazonS3Url.toString();
|
||||
log.info("File '{}' uploaded successfully to Amazon S3 with URL: {}", fileName, fileUrl);
|
||||
return fileUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -115,12 +120,15 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
|
||||
public InputStream getFile(String s3Folder, String filePath) {
|
||||
try {
|
||||
String fileName = Utils.extractFileName(filePath);
|
||||
String path = s3Folder + "/" + fileName;
|
||||
// Decode the file name to handle special characters like '+' correctly
|
||||
String decodedFileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8.toString());
|
||||
|
||||
String path = s3Folder + "/" + decodedFileName;
|
||||
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
|
||||
S3Object s3Object = amazonS3.getObject(getObjectRequest);
|
||||
log.info("File fetched successfully from Amazon S3: {}", fileName);
|
||||
return s3Object.getObjectContent();
|
||||
} catch (AmazonS3Exception e) {
|
||||
} catch (Exception e) {
|
||||
log.error("Error occurred while getting file from Amazon S3: {}", e);
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.GET_ERROR_S3));
|
||||
|
||||
@@ -91,13 +91,6 @@ public class ApplicationAmendmentRequestServiceImpl implements ApplicationAmendm
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ApplicationAmendmentRequestResponse updateApplicationAmendment(HttpServletRequest request, Long id, ApplicationAmendmentRequestBean applicationAmendmentRequestBean) {
|
||||
ApplicationAmendmentRequestEntity amendment = applicationAmendmentRequestDao.validateApplicationAmendmentRequest(id);
|
||||
|
||||
if (Boolean.FALSE.equals(validator.checkIsBeneficiary())) {
|
||||
validator.validatePreInstructor(request, amendment.getApplicationEvaluationEntity().getUserId());
|
||||
} else {
|
||||
validator.validateUserId(request, amendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getUserId());
|
||||
}
|
||||
return applicationAmendmentRequestDao.updateApplicationAmendment(id,applicationAmendmentRequestBean);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,29 +1,24 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.dao.ApplicationEvaluationDao;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
|
||||
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationStatusForEvaluation;
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.EvaluationDocumentRequest;
|
||||
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationResponse;
|
||||
|
||||
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
|
||||
import net.gepafin.tendermanagement.service.ApplicationEvaluationService;
|
||||
import net.gepafin.tendermanagement.service.AssignedApplicationsService;
|
||||
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.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class ApplicationEvaluationServiceImpl implements ApplicationEvaluationService {
|
||||
@@ -36,6 +31,9 @@ public class ApplicationEvaluationServiceImpl implements ApplicationEvaluationSe
|
||||
private AssignedApplicationsService assignedApplicationsService;
|
||||
@Autowired
|
||||
private AssignedApplicationsRepository assignedApplicationsRepository;
|
||||
@Autowired
|
||||
private ApplicationEvaluationService applicationEvaluationService;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ApplicationEvaluationResponse createOrUpdateApplicationEvaluation(
|
||||
@@ -54,31 +52,12 @@ public class ApplicationEvaluationServiceImpl implements ApplicationEvaluationSe
|
||||
@Transactional(readOnly = true)
|
||||
public ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(
|
||||
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)
|
||||
);
|
||||
}
|
||||
UserEntity preInstructor = validator.validateUser(request);
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByApplicationIdOrIdAndIsDeletedFalse(applicationId,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)
|
||||
));
|
||||
validator.validatePreInstructor(request, assignedApplications.getUserId());
|
||||
|
||||
return applicationEvaluationDao.getApplicationEvaluationByApplicationId(
|
||||
request,
|
||||
preInstructor,
|
||||
assignedApplications.getApplication().getId(),
|
||||
assignedApplications.getId()
|
||||
applicationId,
|
||||
assignedApplicationId
|
||||
);
|
||||
}
|
||||
|
||||
@@ -93,4 +72,10 @@ public class ApplicationEvaluationServiceImpl implements ApplicationEvaluationSe
|
||||
public ApplicationEvaluationEntity validateApplicationEvaluation(Long applicationEvaluationId) {
|
||||
return applicationEvaluationDao.validateApplicationEvaluation(applicationEvaluationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationEvaluationEntity validateApplicationEvaluationByApplicationId(Long applicationId) {
|
||||
return applicationEvaluationDao.validateApplicationEvaluationByApplicationId(applicationId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.AppointmentDao;
|
||||
import net.gepafin.tendermanagement.model.request.CreateAppointmentRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UploadDocToExternalSystemRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AppointmentCreationResponse;
|
||||
import net.gepafin.tendermanagement.model.response.DocumentUploadResponse;
|
||||
import net.gepafin.tendermanagement.model.response.NdgResponse;
|
||||
import net.gepafin.tendermanagement.service.AppointmentService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AppointmentServiceImpl implements AppointmentService {
|
||||
|
||||
@Autowired
|
||||
private AppointmentDao appointmentDao;
|
||||
|
||||
@Override
|
||||
public NdgResponse checkNdgForAppointment(HttpServletRequest request, Long applicationId) {
|
||||
|
||||
return appointmentDao.checkNdgForAppointment(applicationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AppointmentCreationResponse createAppointmentForApplication(HttpServletRequest request, Long applicationId, CreateAppointmentRequest createAppointmentRequest) {
|
||||
|
||||
return appointmentDao.createAppointment(applicationId, createAppointmentRequest);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DocumentUploadResponse uploadDocToExternalSystem(HttpServletRequest request, Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
|
||||
|
||||
return appointmentDao.uploadDocumentToExternalSystem(documentId, docToExternalSystemRequest);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import net.gepafin.tendermanagement.dao.AssignedApplicationsDao;
|
||||
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
import net.gepafin.tendermanagement.service.AssignedApplicationsService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
@@ -45,7 +46,7 @@ public class AssignedApplicationsServiceImpl implements AssignedApplicationsServ
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, AssignedApplicationsRequest updatedAssignedApplicationRequest) {
|
||||
public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, UpdateAssignedApplicationRequest updatedAssignedApplicationRequest) {
|
||||
return assignedApplicationsDao.updateAssignedApplication(request, id, updatedAssignedApplicationRequest);
|
||||
}
|
||||
|
||||
|
||||
@@ -111,9 +111,8 @@ public class CompanyServiceImpl implements CompanyService {
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId) {
|
||||
UserEntity userEntity =validator.validateUser(request);
|
||||
return delegationDao.getCompanyDelegation(userEntity, companyId);
|
||||
public CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId,Long applicationId) {
|
||||
return delegationDao.getCompanyDelegation(request, companyId,applicationId);
|
||||
}
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.DocumentDao;
|
||||
import net.gepafin.tendermanagement.entities.DocumentEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.DocumentTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.response.DocumentResponseBean;
|
||||
import net.gepafin.tendermanagement.service.DocumentService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@@ -22,9 +25,13 @@ public class DocumentServiceImpl implements DocumentService {
|
||||
@Autowired
|
||||
private DocumentDao documentDao;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
@Override
|
||||
public List<DocumentResponseBean> uploadFile(List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
|
||||
return documentDao.uploadFiles(files,sourceId,sourceType,fileType);
|
||||
public List<DocumentResponseBean> uploadFile(HttpServletRequest request,List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
|
||||
Map<String, Object> userInfo = validator.getUserInfoFromToken(request);
|
||||
Long userId = validator.getUserId(userInfo);
|
||||
return documentDao.uploadFiles(userId,files,sourceId,sourceType,fileType);
|
||||
}
|
||||
@Override
|
||||
public void deleteFile(Long documentId) {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.dao.NotificationDao;
|
||||
import net.gepafin.tendermanagement.enums.NotificationEnum;
|
||||
import net.gepafin.tendermanagement.model.request.NotificationReq;
|
||||
import net.gepafin.tendermanagement.model.response.NotificationResponse;
|
||||
import net.gepafin.tendermanagement.service.NotificationService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hibernate.internal.util.collections.CollectionHelper.listOf;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class NotificationServiceImpl implements NotificationService {
|
||||
|
||||
@Autowired
|
||||
private NotificationDao notificationDao;
|
||||
|
||||
@Override
|
||||
public NotificationResponse sendNotification(Long userId, NotificationReq notificationReq, Long companyId) {
|
||||
|
||||
log.info("Sending notification to user {} with content: {}", userId, notificationReq.getMessage());
|
||||
notificationReq.setUserId(userId);
|
||||
notificationReq.setCompanyIds(listOf(companyId));
|
||||
return notificationDao.sendNotification(notificationReq);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NotificationResponse getNotificationById(HttpServletRequest servletRequest, Long id) {
|
||||
|
||||
return notificationDao.getNotificationById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<NotificationResponse> getNotificationByUserId(HttpServletRequest servletRequest, Long userId, Long companyId, List<NotificationEnum> statuses) {
|
||||
|
||||
return notificationDao.getNotificationByUserId(userId, companyId, statuses);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NotificationResponse updateNotificationStatus(HttpServletRequest request, Long id, NotificationEnum status) {
|
||||
|
||||
return notificationDao.updateNotificationStatus(id, status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteNotification(HttpServletRequest request, Long id) {
|
||||
|
||||
notificationDao.deleteNotification(id);
|
||||
return;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<NotificationResponse> getNotificationsByCompanyIdAndUserId(Long userId, Long companyId, List<NotificationEnum> statuses) {
|
||||
return notificationDao.getNotificationByCompanyIdAndUserId(userId, companyId, statuses);
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,7 @@ import net.gepafin.tendermanagement.dao.S3PathConfig;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.DocumentEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationAmendmentRequestRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationSignedDocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
import net.gepafin.tendermanagement.service.AmazonS3Service;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -73,6 +70,9 @@ public class S3ReUploadMigrationService {
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestRepository applicationAmendmentRequestRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
@Autowired
|
||||
private DocumentDao documentDao;
|
||||
|
||||
@@ -107,7 +107,7 @@ public class S3ReUploadMigrationService {
|
||||
Long callId = null;
|
||||
Long applicationId = null;
|
||||
Long amendmentId = null;
|
||||
|
||||
Long evaluationId = null;
|
||||
if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(document.getSource())) {
|
||||
callId = document.getSourceId();
|
||||
} else if (DocumentSourceTypeEnum.APPLICATION.getValue().equalsIgnoreCase(document.getSource())) {
|
||||
@@ -120,8 +120,14 @@ public class S3ReUploadMigrationService {
|
||||
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
} else if(DocumentSourceTypeEnum.EVALUATION.getValue().equalsIgnoreCase(document.getSource())){
|
||||
evaluationId = document.getSourceId();
|
||||
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
|
||||
applicationId = applicationEntity.getId();
|
||||
callId = applicationEntity.getCall().getId();
|
||||
}
|
||||
|
||||
|
||||
documentDao.deleteFileFromS3(document,callId,applicationId,amendmentId);
|
||||
processDocuments++;
|
||||
|
||||
|
||||
@@ -126,8 +126,8 @@ public class UserServiceImpl implements UserService {
|
||||
}
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId) {
|
||||
public List<UserResponseBean> getAllUsers(HttpServletRequest request, List<Long> roleIds) {
|
||||
UserEntity user=validator.validateUser(request);
|
||||
return userDao.getAllUsers(user, roleId);
|
||||
return userDao.getAllUsers(user, roleIds);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.UserActionEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.entities.VersionHistoryEntity;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.UserActionRequest;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.repositories.UserActionsRepository;
|
||||
|
||||
@@ -28,7 +28,6 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
@@ -45,12 +44,12 @@ import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientForbiddenExce
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientNotFoundException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientUnauthorizedException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientValidationException;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
@@ -59,6 +58,9 @@ import static org.apache.commons.lang3.StringUtils.isEmpty;
|
||||
|
||||
public class Utils {
|
||||
|
||||
// @Autowired
|
||||
// private static TokenProvider tokenProvider;
|
||||
|
||||
public static final Logger log = LoggerFactory.getLogger(Utils.class);
|
||||
|
||||
private static final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
||||
@@ -580,4 +582,112 @@ public class Utils {
|
||||
// Clear the RequestContextHolder after task execution
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
}
|
||||
|
||||
public static String generateAuthTokenForLoginToOdessa() {
|
||||
|
||||
try {
|
||||
// Your weak secret key
|
||||
String secretKey = GepafinConstant.AUTH_JWT_SECRET_KEY;
|
||||
|
||||
// Header
|
||||
String header = GepafinConstant.JWT_ALGO_HEADER;
|
||||
String encodedHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Payload
|
||||
String payload = "{\"iat\":" + (System.currentTimeMillis() / 1000) + "}";
|
||||
String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Combine header and payload
|
||||
String dataToSign = encodedHeader + "." + encodedPayload;
|
||||
|
||||
// Sign the token manually
|
||||
Mac mac = Mac.getInstance(GepafinConstant.HMAC_ALGO);
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), GepafinConstant.HMAC_ALGO);
|
||||
mac.init(secretKeySpec);
|
||||
byte[] signatureBytes = mac.doFinal(dataToSign.getBytes(StandardCharsets.UTF_8));
|
||||
String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(signatureBytes);
|
||||
|
||||
// Return the final JWT
|
||||
return dataToSign + "." + signature;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to generate JWT token", e);
|
||||
}
|
||||
}
|
||||
|
||||
// public static void setHttpServletRequestForNdgProcess(HttpServletRequest originalRequest) {
|
||||
//
|
||||
// // Validate original request
|
||||
// if (originalRequest == null) {
|
||||
// throw new IllegalArgumentException("Original request cannot be null.");
|
||||
// }
|
||||
//
|
||||
// // Create a mock request
|
||||
// Claims tokenClaims = tokenProvider.getClaimsFromToken(tokenProvider.extractTokenFromRequest(originalRequest));
|
||||
// MockHttpServletRequest mockRequest = new MockHttpServletRequest();
|
||||
// mockRequest.setRequestURI(originalRequest.getRequestURI());
|
||||
// mockRequest.setMethod(originalRequest.getMethod());
|
||||
//
|
||||
// // Copy essential headers and attributes from the original request
|
||||
// Enumeration<String> headerNames = originalRequest.getHeaderNames();
|
||||
// while (headerNames.hasMoreElements()) {
|
||||
// String headerName = headerNames.nextElement();
|
||||
// String headerValue = originalRequest.getHeader(headerName);
|
||||
// if (headerValue != null) {
|
||||
// mockRequest.addHeader(headerName, headerValue);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Set a specific attribute if required
|
||||
// if (originalRequest.getAttribute(GepafinConstant.USER_ACTION_ID) != null) {
|
||||
// mockRequest.setAttribute(GepafinConstant.USER_ACTION_ID, originalRequest.getAttribute(GepafinConstant.USER_ACTION_ID));
|
||||
// }
|
||||
//
|
||||
// ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
|
||||
// RequestContextHolder.setRequestAttributes(attributes);
|
||||
// // Log successful context setting
|
||||
// log.info("Successfully set mock request for NDG process with URI: {}", mockRequest.getRequestURI());
|
||||
// }
|
||||
|
||||
public static Long extractHubIdFromPayload(String payload) {
|
||||
|
||||
Long hubId;
|
||||
try {
|
||||
String[] parts = payload.split(":");
|
||||
if (parts.length > 2) {
|
||||
hubId = Long.valueOf(parts[2]);
|
||||
return hubId;
|
||||
} else {
|
||||
hubId = null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("No Hub id present in payload", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Method to convert a JSON string to an object of type T
|
||||
public static <T> T convertStringToObject(String jsonString, Class<T> clazz) {
|
||||
try {
|
||||
return mapper.readValue(jsonString, clazz);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
// Handle the exception appropriately (e.g., throw a custom exception)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Method to convert an object of type T to a JSON string
|
||||
public static <T> String convertObjectToString(T object) {
|
||||
try {
|
||||
return mapper.writeValueAsString(object);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
// Handle the exception appropriately (e.g., throw a custom exception)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String createChannelForUserAndCompany(Long userId, Long companyId) {
|
||||
return GepafinConstant.COMMON_SINGLE_CHANNEL_PREFIX + userId + GepafinConstant.COMPANY_PREFIX + companyId;
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,8 @@ public class Validator {
|
||||
validateHubId(request, companyEntity.getHub().getId());
|
||||
if (checkIsSuperAdmin()) {
|
||||
return companyEntity;
|
||||
} else if (checkIsInstructorManager()) {
|
||||
return companyEntity;
|
||||
}
|
||||
Map<String, Object> userInfo = tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
companyService.validateUserWithCompny(getUserId(userInfo), companyId);
|
||||
@@ -105,7 +107,7 @@ public class Validator {
|
||||
}
|
||||
}
|
||||
|
||||
private Long getUserId(Map<String, Object> userInfo) {
|
||||
public Long getUserId(Map<String, Object> userInfo) {
|
||||
return Long.parseLong(userInfo.get("userId").toString());
|
||||
}
|
||||
|
||||
@@ -127,8 +129,11 @@ public class Validator {
|
||||
UserEntity requestedUser = userService.validateUser(userId);
|
||||
|
||||
validateHubId(request, requestedUser.getHub().getId());
|
||||
if (Boolean.FALSE.equals(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_SUPER_ADMIN.getValue()))
|
||||
&& Boolean.FALSE.equals(user.getId().equals(userId))) {
|
||||
// if (Boolean.FALSE.equals(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_SUPER_ADMIN.getValue()))
|
||||
// && Boolean.FALSE.equals(user.getId().equals(userId)))
|
||||
if (checkIsSuperAdmin() || checkIsInstructorManager()) {
|
||||
|
||||
} else if(Boolean.FALSE.equals(user.getId().equals(userId))) {
|
||||
throw new ForbiddenAccessException(Status.FORBIDDEN,
|
||||
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
@@ -164,6 +169,11 @@ public class Validator {
|
||||
validateHubId(request, preInstructorUser.getHub().getId());
|
||||
}
|
||||
return preInstructorUser;
|
||||
} else if (checkIsInstructorManager()) {
|
||||
if (preInstructorUserId != null) {
|
||||
validateHubId(request, preInstructorUser.getHub().getId());
|
||||
}
|
||||
return preInstructorUser;
|
||||
} else if (checkIsPreInstructor()) {
|
||||
return validateUserId(request, preInstructorUserId);
|
||||
} else {
|
||||
@@ -171,5 +181,18 @@ public class Validator {
|
||||
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Boolean checkIsInstructorManager() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication != null && authentication.isAuthenticated()) {
|
||||
// Check if the user has the ROLE_INSTRUCTOR_MANAGER authority
|
||||
for (GrantedAuthority authority : authentication.getAuthorities()) {
|
||||
if (RoleStatusEnum.ROLE_INSTRUCTOR_MANAGER.getValue().equals(authority.getAuthority())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import io.swagger.v3.oas.annotations.media.ExampleObject;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationStatusForEvaluation;
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.EvaluationDocumentRequest;
|
||||
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationResponse;
|
||||
import net.gepafin.tendermanagement.model.util.Response;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
|
||||
@@ -16,6 +16,8 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ApplicationEvaluationApi {
|
||||
|
||||
@Operation(summary = "API to create or update ApplicationEvaluation",
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package net.gepafin.tendermanagement.web.rest.api;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.ExampleObject;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.model.request.CreateAppointmentRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UploadDocToExternalSystemRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AppointmentCreationResponse;
|
||||
import net.gepafin.tendermanagement.model.response.DocumentUploadResponse;
|
||||
import net.gepafin.tendermanagement.model.response.NdgResponse;
|
||||
import net.gepafin.tendermanagement.model.util.Response;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
|
||||
public interface AppointmentApi {
|
||||
|
||||
@Operation(summary = "API to check or create ndg.", responses = { @ApiResponse(responseCode = "200", description = "OK"),
|
||||
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
|
||||
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
|
||||
@GetMapping(value = "/application/{applicationId}/check-ndg", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Response<NdgResponse>> checkNdgForAppointment(HttpServletRequest request,
|
||||
@Parameter(description = "The application id", required = true) @PathVariable(value = "applicationId", required = true) Long applicationId);
|
||||
|
||||
@Operation(summary = "API to create appointment.", responses = { @ApiResponse(responseCode = "200", description = "OK"),
|
||||
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
|
||||
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
|
||||
@PostMapping(value = "/application/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Response<AppointmentCreationResponse>> createAppointment(HttpServletRequest request,
|
||||
@Parameter(description = "The application id", required = true) @PathVariable(value = "applicationId", required = true) Long applicationId,
|
||||
@RequestBody CreateAppointmentRequest createAppointmentRequest);
|
||||
|
||||
@Operation(summary = "API to Upload document to external system.", responses = { @ApiResponse(responseCode = "200", description = "OK"),
|
||||
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
|
||||
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
|
||||
@PostMapping(value = "/document/{documentId}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Response<DocumentUploadResponse>> uploadDocumentToExternalSystem(HttpServletRequest request,
|
||||
@Parameter(description = "The document id", required = true) @PathVariable(value = "documentId", required = true) Long documentId,
|
||||
@RequestBody UploadDocToExternalSystemRequest docToExternalSystemRequest);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
import net.gepafin.tendermanagement.model.util.Response;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
|
||||
@@ -32,7 +33,7 @@ public interface AssignedApplicationsApi {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
|
||||
})
|
||||
@PostMapping(value = "/application/{applicationId}")
|
||||
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
|
||||
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')|| hasRole('ROLE_INSTRUCTOR_MANAGER')")
|
||||
public ResponseEntity<Response<AssignedApplicationsResponse>> createAssignedApplications(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "ID of the application", required = true) @PathVariable Long applicationId,
|
||||
@@ -50,7 +51,7 @@ public interface AssignedApplicationsApi {
|
||||
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
|
||||
@DeleteMapping(value = "/{id}")
|
||||
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
|
||||
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')|| hasRole('ROLE_INSTRUCTOR_MANAGER')")
|
||||
ResponseEntity<Response<Void>> deleteAssignedApplication(HttpServletRequest request,
|
||||
@Parameter(description = "The assigned application id", required = true) @PathVariable("id") Long id);
|
||||
|
||||
@@ -78,10 +79,10 @@ public interface AssignedApplicationsApi {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
|
||||
})
|
||||
@PutMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
|
||||
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')|| hasRole('ROLE_INSTRUCTOR_MANAGER')")
|
||||
public ResponseEntity<Response<AssignedApplicationsResponse>> updateAssignedApplication(HttpServletRequest request,
|
||||
@Parameter(description = "The Assigned Application id", required = true) @PathVariable("id") Long id,
|
||||
@Parameter(description = "Assigned Application request object", required = true) @Valid @RequestBody AssignedApplicationsRequest assignedApplicationsRequest);
|
||||
@Parameter(description = "Assigned Application request object", required = true) @Valid @RequestBody UpdateAssignedApplicationRequest assignedApplicationsRequest);
|
||||
|
||||
@Operation(summary = "Api to get an assigned application by id",
|
||||
responses = {
|
||||
|
||||
@@ -33,7 +33,7 @@ public interface CommunicationApi {
|
||||
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
|
||||
@PostMapping(value = "/{amendmentId}", produces = { "application/json" })
|
||||
@PreAuthorize("hasRole('ROLE_PRE_INSTRUCTOR') || hasRole('ROLE_BENEFICIARY')")
|
||||
@PreAuthorize("hasRole('ROLE_PRE_INSTRUCTOR') || hasRole('ROLE_BENEFICIARY') || hasRole('ROLE_INSTRUCTOR_MANAGER')")
|
||||
ResponseEntity<Response<CommunicationResponseBean>> addCommentToAmendmentRequest(HttpServletRequest request,
|
||||
@RequestBody @Parameter CommunicationRequestBean communicationResponseBean, @PathVariable(value = "amendmentId") Long amendmentId);
|
||||
|
||||
@@ -55,7 +55,7 @@ public interface CommunicationApi {
|
||||
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
|
||||
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
|
||||
@PutMapping(value = "/{amendmentId}/{commentId}", produces = { "application/json" })
|
||||
@PreAuthorize("hasRole('ROLE_PRE_INSTRUCTOR') || hasRole('ROLE_BENEFICIARY')")
|
||||
@PreAuthorize("hasRole('ROLE_PRE_INSTRUCTOR') || hasRole('ROLE_BENEFICIARY') || hasRole('ROLE_INSTRUCTOR_MANAGER')")
|
||||
ResponseEntity<Response<CommunicationResponseBean>> updateCommunicationAmendment(HttpServletRequest request,
|
||||
@RequestBody @Parameter CommunicationRequestBean communicationResponseBean, @PathVariable(value = "amendmentId") Long amendmentId, @PathVariable(value = "commentId") Long commentId);
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user