Resolved Conflicts

This commit is contained in:
rajesh
2025-06-03 19:23:46 +05:30
125 changed files with 4072 additions and 541 deletions

24
pom.xml
View File

@@ -251,6 +251,24 @@
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.10.0</version>
</dependency>
<!-- Jakarta email support -->
<!-- https://jakarta.ee/specifications/mail/ -->
<!-- https://github.com/jakartaee/mail-api -->
<!-- https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
@@ -271,8 +289,8 @@
<artifactId>liquibase-maven-plugin</artifactId>
<configuration>
<propertyFile>src/main/resources/application.properties</propertyFile>
</configuration>
</plugin>
</plugins>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -510,6 +510,68 @@ public class GepafinConstant {
public static final String APPLICATION_USER_ID="applicationUserId";
public static final String INVALID_USER_ID="invalid.user";
public static final String COMPANY_NAME="companyName";
public static final String TABLE_COLUMNS="table_columns";
public static final String PREDEFINED="predefined";
public static final String EBABLE_CSV="enableCsv";
public static final String LABEL_CSV="labelCsv";
public static final String GET="get";
public static final String REPORT_COLUMNS="reportColumns";
public static final String FIELD_TYPE="fieldtype";
public static final String ENABLE_FORMULA="enableFormula";
public static final String STATE_FIELD_DATA="stateFieldData";
public static final String REPORT_ENABLE="reportEnable";
public static final String TABLE="table";
public static final String GET_FIELD_TYPE="getFieldType";
public static final String GET_APPLICATION_FORM_ID="getApplicationFormId";
public static final String GET_APPLICATION_ID="getApplicationId";
public static final String GET_ID="getId";
public static final String GET_CLASS="getClass";
public static final String GET_FORM_ID="getFormId";
public static final String GET_FIELD_ID="getFieldId";
public static final String GET_FIELD_LABEL="getFieldLabel";
public static final String GET_FIELD_VALUE="getFieldValue";
public static final String GET_REPORT_ENABLE="getReportEnable";
public static final String GET_REPORT_HEADER="getReportHeader";
public static final String APPOINTMENT_ID="appointmentId";
public static final String APPLICATION_STATUS="applicationStatus";
public static final String RINALDO_EMAIL = "rinaldo.bonazzo@bflows.net";
public static final String RESEND_EMAIL_SENT_SUCCESS_MSG = "resend.email.sent.success.msg";
public static final String RESEND_EMAIL_SENT_FAILED_MSG = "resend.email.sent.failed.msg";
public static final String REMINDER_EMAIL_FAILED_MSG = "reminder.email.sent.failed.msg";
public static final String READMIT_APPLICATION_SUCCESS = "application.readmit.success";
public static final String NO_EMAIL_LOG_FOUND = "no.email.log.msg";
public static final String USER_ACTION_ID_NOT_FOUND = "user.action.id.not.found";
public static final String CAUSE_STRING = "cause" ;
public static final String ERROR_DESCRIPTION_STRING = "errorDescription" ;
public static final String ERROR_STRING = "errors";
public static final String PROTOCOL_SERVICE_URL="http://65.108.55.96:8080";
public static final String PROTOCOL_SERVICE_BEARER_TOKEN="/auth/login";
public static final String PROTOCOL_SERVICE_CREATE_PROTOCOL="/documenti/protocollaUD";
public static final String PROTOCOL_CALL_NAME="BANDO";
public static final String PROTOCOL_DOC_URL="DOC_URL";
public static final String PROTOCOL_COMPANY_NAME_VAT_NUMBER="OGGETTO_PG";
public static final String PROTOCOL_DOC_HASH="URL_CONTENT_HASH";
public static final String PROTOCOL_TIPO_PROTOCOLLAZIONE="TIPO_PROTOCOLLAZIONE";
public static final String PROTOCOL_TIPO_CORRISPONDENTE_COMPANY="tipoCorrispondente";
public static final String PROTOCOL_COMPANY_NAME="denominazione";
public static final String PROTOCOL_MEZZO="mezzo";
public static final String PROTOCOL_INDIRIZZO_PEC="indirizzoPec";
public static final String PROTOCOL_COMPANY_VAT_NUMBER="identificativo";
public static final String PROTOCOL_CODICE_UO="codiceUo";
public static final String PROTOCOL_COMPETENTE="competente";
public static final String PROTOCOL_TIPO_CORRISPONDENTE="tipoCorrispondente";
public static final String PROTOCOL_MITTENTE="mittente";
public static final String PROTOCOL_DESTINATARI="destinatari";
public static final String PROTOCOL_EXTERNAL_YEAR="ANNO_PG";
public static final String PROTOCOL_EXTERNAL_NUMBER="NUM_PG";
public static final String PROTOCOL_EXTERNAL_DATE="DATA_PG_DT";
public static final String PROTOCOL_DOC_SUFFIX="#noauth";
}

View File

@@ -1,5 +1,6 @@
package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.criteria.CriteriaBuilder;
@@ -26,6 +27,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundExceptio
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
@@ -140,6 +142,12 @@ public class ApplicationAmendmentRequestDao {
@Autowired
private ApplicationDao applicationDao;
@Autowired
private EmailLogRepository emailLogRepository;
@Autowired
private EmailDao emailDao;
public ApplicationAmendmentRequestResponse getApplicationDataForAmendment(Long applicationEvaluationId) {
log.info("Fetching the application data for the Amendment process {}", applicationEvaluationId);
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluation(applicationEvaluationId);
@@ -151,7 +159,8 @@ public class ApplicationAmendmentRequestDao {
String file=applicationEvaluationEntity.getFile();
String checkList=applicationEvaluationEntity.getChecklist();
if(file != null){
evaluationFileRequests=Utils.convertJsonStringToList(file,FieldRequest.class);
log.info("Parsing evaluation file data for evaluationId={}", applicationEvaluationId);
evaluationFileRequests=Utils.convertJsonStringToList(file,FieldRequest.class);
}
if(applicationEvaluationEntity.getEvaluationVersion().equals(EvaluationVersionEnum.V1.getValue())) {
checklistValidationForEvaluationV1(evaluationFileRequests, checkList, checklistRequests);
@@ -300,6 +309,15 @@ public class ApplicationAmendmentRequestDao {
log.info("Application submitted successfully for amendment", applicationAmendmentRequestResponse);
if (Boolean.TRUE.equals(applicationAmendmentRequestResponse.getIsSendEmail())) {
emailNotificationDao.sendMailToNotifyBeneficiaryRegardingNewAmendment(applicationAmendmentRequestEntity);
EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
List<EmailSendResponse> responses = List.of(emailSendResponse);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
saveEmailSendResponse(emailSendResponse, applicationAmendmentRequestEntity);
applicationAmendmentRequestResponse.setEmailSendResponse(responses);
}
else{
applicationAmendmentRequestResponse.setEmailSendResponse(Collections.emptyList());
}
}
return applicationAmendmentRequestResponse;
}
@@ -309,6 +327,7 @@ public class ApplicationAmendmentRequestDao {
applicationAmendmentRequestEntity.setNote(applicationAmendmentRequest.getNote());
applicationAmendmentRequestEntity.setResponseDays(applicationAmendmentRequest.getResponseDays());
if(applicationAmendmentRequest.getResponseDays()==null || applicationAmendmentRequest.getResponseDays() < 0){
log.warn("Invalid responseDays received: {}", applicationAmendmentRequest.getResponseDays());
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.RESPONSE_DAYS_NOT_NULL));
}
applicationAmendmentRequestEntity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()).plusDays(applicationAmendmentRequest.getResponseDays()));
@@ -359,8 +378,11 @@ public class ApplicationAmendmentRequestDao {
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(
applicationEvaluationEntity.getAssignedApplicationsEntity().getApplication(), protocolNumber,
userEntity.getHub().getId(),false);
protocolDao.saveProtocolEntity(protocolEntity);
applicationAmendmentRequestEntity.setProtocol(protocolEntity);
ApplicationAmendmentRequestEntity applicationAmendment = saveApplicationAmendmentRequestEntity(applicationAmendmentRequestEntity, null, VersionActionTypeEnum.INSERT);
log.info("Amendment request saved with ID={}", applicationAmendment.getId());
String evaluationStatusType = applicationEvaluationEntity.getStatus();
if (Boolean.FALSE.equals(evaluationStatusType.equals((ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue())))){
// applicationEvaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
@@ -399,7 +421,7 @@ public class ApplicationAmendmentRequestDao {
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplication).newData(assignedApplicationsEntity).build());
}
log.info("Amendment creation process completed successfully for applicationId={}, evaluationId={}", applicationId, applicationEvaluationId);
return applicationAmendment;
}
private void setAmendmentDocuments(String amendmentNotes, String amendmentFieldRequest,
@@ -490,7 +512,7 @@ public class ApplicationAmendmentRequestDao {
}
public DocumentResponseBean createDocumentResponseBean(String documentId) {
log.info("Initiating document response creation for documentId={}", documentId);
if (!StringUtils.isEmpty(documentId)) {
Optional<DocumentEntity> documentEntity = documentRepository.findByIdAndNotDeleted(Long.valueOf(documentId));
if(documentEntity.isPresent()){
@@ -506,6 +528,7 @@ public class ApplicationAmendmentRequestDao {
Long hubId = applicationEntity.getHubId();
HubEntity hubEntity = hubService.valdateHub(hubId);
response.setEmailSendResponse(entity.getEmailSendResponse());
response.setId(entity.getId());
response.setApplicationId(entity.getApplicationId());
response.setApplicationEvaluationId(entity.getApplicationEvaluationEntity().getId());
@@ -647,13 +670,15 @@ public class ApplicationAmendmentRequestDao {
public ApplicationAmendmentRequestResponse getApplicationAmendmentRequestById(Long id) {
log.info("Fetching application amendment with ID: {}", id);
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
ApplicationAmendmentRequestResponse response = convertEntityToResponse(applicationAmendmentRequestEntity,true);
log.info("Application Amendment fetched successfully by ID: {}", response);
return response;
ApplicationAmendmentRequestResponse response = convertEntityToResponse(applicationAmendmentRequestEntity,true);
response.setEmailSendResponse(applicationAmendmentRequestEntity.getEmailSendResponse());
return response;
}
public List<GetAllAmendmentResponseBean> getAllApplicationAmendmentRequest(HttpServletRequest request, Long userId) {
log.info("Entering getAllApplicationAmendmentRequest with userId={}", userId);
if (validator.checkIsPreInstructor() && userId == null) {
log.warn("Access denied: Pre-instructor must provide userId for amendment request retrieval.");
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.USER_ID_NOT_NULL_MSG));
}
if (userId != null) {
@@ -696,9 +721,11 @@ public class ApplicationAmendmentRequestDao {
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));
log.warn("Permission denied: Beneficiary tried to update amendment ID {} with status RESPONSE_RECEIVED", id);
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
}
if(Boolean.FALSE.equals(isBeneficiary) && existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.AWAITING.getValue())){
log.warn("Permission denied: Non-beneficiary tried to update amendment ID {} with status AWAITING", id);
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
}
@@ -721,10 +748,12 @@ public class ApplicationAmendmentRequestDao {
}
existingApplicationAmendment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
if(updateRequest.getAmendmentDocuments()!=null && Boolean.FALSE.equals(updateRequest.getAmendmentDocuments().isEmpty())) {
log.debug("Setting amendment documents for amendment ID: {}", id);
setAmendmentDocuments(updateRequest.getAmendmentNotes(),updateRequest.getAmendmentDocuments(), existingApplicationAmendment);
}
ApplicationAmendmentRequestEntity updatedApplicationAmendment = saveApplicationAmendmentRequestEntity(existingApplicationAmendment,oldApplicationAmendmentEntity,VersionActionTypeEnum.UPDATE);
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment,false);
log.info("Successfully updated ApplicationAmendmentRequest with ID: {}", id);
log.info("Application Amendment updated successfully: {}", response);
return response;
}
@@ -1020,6 +1049,7 @@ public class ApplicationAmendmentRequestDao {
public List<ApplicationAmendmentRequestResponse> getAllAmendmentRequestByBeneficiaryId(Long beneficiaryUserId) {
log.info("Fetching all amendment requests for beneficiaryUserId={}", beneficiaryUserId);
UserEntity userEntity = userService.validateUser(beneficiaryUserId);
List<ApplicationAmendmentRequestEntity> entities =
applicationAmendmentRequestRepository.findByUserId(beneficiaryUserId);
@@ -1032,29 +1062,34 @@ public class ApplicationAmendmentRequestDao {
public ApplicationAmendmentRequestResponse closeAmendmentRequest(Long id, CloseAmendmentRequest closeAmendmentRequest) {
log.info("Closing application amendement with ID: {}", id);
ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
ApplicationAmendmentRequestEntity existingApplicationAmendment = validatApplicationAmendmentRequestByListStatus(id,List.of(ApplicationAmendmentRequestEnum.AWAITING.getValue(),ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue()));
//cloned entity for old data and versioning
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment);
List<ApplicationAmendmentRequestEntity> amendmentRequestList = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
existingApplicationAmendment.getApplicationEvaluationEntity().getId()
);
log.debug("Found {} amendment requests for ApplicationEvaluationId={}", amendmentRequestList.size(), existingApplicationAmendment.getApplicationEvaluationEntity().getId());
// Check if this is the last amendment being closed
boolean isLastRemaining = amendmentRequestList.stream()
.filter(amendment -> !amendment.getId().equals(id)) // Exclude the current amendment
.allMatch(amendment -> amendment.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()));
.allMatch(amendment -> amendment.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()) || amendment.getStatus().equals(ApplicationAmendmentRequestEnum.EXPIRED.getValue()));
if (isLastRemaining) {
log.info("The current amendment is the last remaining one to be closed.");
applicationAmendmentRequestDao.calculateEndDateAndSuspensionDays(existingApplicationAmendment.getApplicationEvaluationEntity());
}
setIfUpdated(existingApplicationAmendment::getInternalNote, existingApplicationAmendment::setInternalNote, closeAmendmentRequest.getInternalNote());
setIfUpdated(existingApplicationAmendment::getStatus, existingApplicationAmendment::setStatus, ApplicationAmendmentRequestEnum.CLOSE.getValue());
existingApplicationAmendment.setClosingDate(LocalDateTime.now());
ApplicationAmendmentRequestEntity updatedApplicationAmendment = saveApplicationAmendmentRequestEntity(existingApplicationAmendment, oldApplicationAmendmentEntity,
VersionActionTypeEnum.UPDATE);
if (isLastRemaining) {
log.info("The current amendment is the last remaining one to be closed.");
applicationAmendmentRequestDao.calculateEndDateAndSuspensionDaysOnExpirationOrClosing(existingApplicationAmendment.getApplicationEvaluationEntity());
}
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment,false);
log.info("Updated amendment status to CLOSE for amendment ID: {}", id);
List<ApplicationAmendmentRequestEntity> amendmentRequests = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
existingApplicationAmendment.getApplicationEvaluationEntity().getId());
Boolean allClosed = amendmentRequests.stream().allMatch(amendment -> (amendment.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()) || amendment.getStatus().equals(ApplicationAmendmentRequestEnum.EXPIRED.getValue())));
@@ -1062,24 +1097,28 @@ public class ApplicationAmendmentRequestDao {
ApplicationEntity oldApplicationEntityData = Utils.getClonedEntityForData(application);
if (Boolean.TRUE.equals(allClosed)) {
existingApplicationAmendment.getApplicationEvaluationEntity().setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
if (allClosed) {
ApplicationEvaluationEntity existingApplicationEvaluationEntity = existingApplicationAmendment.getApplicationEvaluationEntity();
ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils.getClonedEntityForData(existingApplicationEvaluationEntity);
existingApplicationEvaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
applicationEvaluationRepository.save(existingApplicationAmendment.getApplicationEvaluationEntity());
log.info("Updated ApplicationEvaluation status to OPEN for ID: {}", existingApplicationEvaluationEntity.getId());
application.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
applicationRepository.save(application);
log.info("Updated Application status to EVALUATION for Application ID: {}", application.getId());
existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().setStatus(AssignedApplicationEnum.OPEN.getValue());
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsDao.validateAssignedApplication(
existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getId());
AssignedApplicationsEntity oldAssignedApplicationData = Utils.getClonedEntityForData(assignedApplicationsEntity);
assignedApplicationsEntity = assignedApplicationsRepository.save(existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity());
existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().setStatus(AssignedApplicationEnum.OPEN.getValue());
assignedApplicationsEntity = assignedApplicationsRepository.save(existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity());
log.info("Updated AssignedApplication status to OPEN for ID: {}", assignedApplicationsEntity.getId());
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.AMENDMENT_CLOSED);
@@ -1104,15 +1143,18 @@ public class ApplicationAmendmentRequestDao {
return response;
}
public ApplicationAmendmentRequestResponse extendResponseDays(Long id, Long newResponseDays) {
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays);
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validatApplicationAmendmentRequestByStatus(id,ApplicationAmendmentRequestEnum.EXPIRED.getValue());
if (newResponseDays != null && newResponseDays > 0) {
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(applicationAmendmentRequestEntity);
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(applicationAmendmentRequestEntity);
Long currentResponseDays = applicationAmendmentRequestEntity.getResponseDays() != null ? applicationAmendmentRequestEntity.getResponseDays() : 0L;
applicationAmendmentRequestEntity.setResponseDays(currentResponseDays + newResponseDays);
applicationAmendmentRequestEntity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now().plusDays(applicationAmendmentRequestEntity.getResponseDays())));
applicationAmendmentRequestEntity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now().plusDays(newResponseDays)));
applicationAmendmentRequestEntity.setStatus(ApplicationAmendmentRequestEnum.AWAITING.getValue());
applicationAmendmentRequestEntity.getApplicationEvaluationEntity().setStatus(ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
applicationAmendmentRequestEntity.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().setStatus(ApplicationStatusTypeEnum.SOCCORSO.getValue());
applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
/** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
@@ -1156,6 +1198,7 @@ public class ApplicationAmendmentRequestDao {
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))) {
log.info("Updating amendment ID {} status from {} to {}", id, existingApplicationAmendment.getStatus(), statusTypeEnum);
existingApplicationAmendment.setStatus(ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue());
existingApplicationAmendment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
applicationAmendmentRequestRepository.save(existingApplicationAmendment);
@@ -1168,12 +1211,15 @@ public class ApplicationAmendmentRequestDao {
return response;
}
public void sendReminderEmail(Long amendmentId) {
public EmailReminderResponse sendReminderEmail(Long amendmentId) {
log.info("Initiating reminder email process for Amendment ID: {}", amendmentId);
ApplicationAmendmentRequestEntity amendment = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(amendmentId)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG)));
.orElseThrow(() -> { log.error("Amendment not found with ID: {}", amendmentId);
return new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG));
});
Optional<ApplicationEvaluationEntity> entityOptional = applicationEvaluationRepository.findByIdAndIsDeletedFalse(amendment.getApplicationEvaluationEntity().getId());
EmailReminderResponse emailReminderResponse = new EmailReminderResponse();
if (entityOptional.isPresent()) {
ApplicationEntity applicationEntity = applicationService.validateApplication(entityOptional.get().getApplicationId());
UserEntity beneficiaryUser = userService.validateUser(applicationEntity.getUserId());
@@ -1183,13 +1229,26 @@ public class ApplicationAmendmentRequestDao {
String body = prepareBody(emailTemplate, amendment, beneficiaryUser);
String email = beneficiaryUser.getEmail();
if (Boolean.TRUE.equals(amendment.getIsEmail()) && email != null && !email.isEmpty()) {
log.info("Sending reminder email to: {}", email);
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, beneficiaryUser.getId(), email,
beneficiaryUser.getId(), applicationEntity.getId(), amendment.getId(), applicationEntity.getCall().getId());
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email), emailLogRequest);
EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
List<EmailSendResponse> responses = List.of(emailSendResponse);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
emailReminderResponse.setEmailSendResponse(responses);
saveEmailSendResponse(emailSendResponse, amendment);
}
else{
emailReminderResponse.setEmailSendResponse(Collections.emptyList());
}
log.info("Reminder email sent successfully for Amendment ID: {}", amendmentId);
} else {
log.warn("Beneficiary email not found or isEmail flag is false for Amendment ID: {}", amendmentId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.BENEFICIARY_EMAIL_NOT_FOUND_MSG));
}
}
return emailReminderResponse;
}
private String prepareSubject(SystemEmailTemplateResponse template, ApplicationAmendmentRequestEntity amendment, UserEntity beneficiary) {
@@ -1219,26 +1278,26 @@ public class ApplicationAmendmentRequestDao {
return Utils.replacePlaceholders(template.getHtmlContent(), bodyPlaceholders);
}
public ApplicationEvaluationEntity calculateEndDateAndSuspensionDays(ApplicationEvaluationEntity applicationEvaluationEntity){
LocalDateTime currentDate=DateTimeUtil.DateServerToUTC(LocalDateTime.now());
LocalDateTime endDate=currentDate.plusDays(applicationEvaluationEntity.getRemainingDays());
Long suspendedDays = ChronoUnit.DAYS.between(applicationEvaluationEntity.getStopDateTime(), currentDate);
ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
applicationEvaluationEntity.setEndDate(endDate);
if(applicationEvaluationEntity.getSuspendedDays() == null) {
applicationEvaluationEntity.setSuspendedDays(0L);
}
applicationEvaluationEntity.setSuspendedDays(applicationEvaluationEntity.getSuspendedDays()+suspendedDays);
ApplicationEvaluationEntity applicationEvaluation = applicationEvaluationRepository.save(applicationEvaluationEntity);
/** 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(oldApplicationEvaluationEntity).newData(applicationEvaluation).build());
return applicationEvaluation;
}
// public ApplicationEvaluationEntity calculateEndDateAndSuspensionDays(ApplicationEvaluationEntity applicationEvaluationEntity){
// LocalDateTime currentDate=DateTimeUtil.DateServerToUTC(LocalDateTime.now());
// LocalDateTime endDate=currentDate.plusDays(applicationEvaluationEntity.getRemainingDays());
// Long suspendedDays = ChronoUnit.DAYS.between(applicationEvaluationEntity.getStopDateTime(), currentDate);
//
// ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
// applicationEvaluationEntity.setEndDate(endDate);
// if(applicationEvaluationEntity.getSuspendedDays() == null) {
// applicationEvaluationEntity.setSuspendedDays(0L);
// }
// applicationEvaluationEntity.setSuspendedDays(applicationEvaluationEntity.getSuspendedDays()+suspendedDays);
// ApplicationEvaluationEntity applicationEvaluation = applicationEvaluationRepository.save(applicationEvaluationEntity);
//
// /** 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(oldApplicationEvaluationEntity).newData(applicationEvaluation).build());
//
// return applicationEvaluation;
//
//
// }
private GetAllAmendmentResponseBean initializeGetAllBasicResponse(ApplicationAmendmentRequestEntity entity) {
GetAllAmendmentResponseBean response = new GetAllAmendmentResponseBean();
@@ -1271,7 +1330,9 @@ public class ApplicationAmendmentRequestDao {
return response;
}
private void softDeleteDocument(Long documentId) {
log.info("Initiating soft delete for Document ID: {}", documentId);
documentService.deleteFile(documentId);
log.info("Document ID: {} soft deleted successfully.", documentId);
}
// public PageableResponseBean<List<ApplicationAmendmentRequestResponse>> getApplicationAmendmentByPaginnation(Long userId, ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
@@ -1390,6 +1451,7 @@ public class ApplicationAmendmentRequestDao {
// }
public PageableResponseBean<List<ApplicationAmendmentRequestViewResponse>> getApplicationAmendmentByPaginationByView(Long userId, ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
log.info("Fetching paginated application amendments for userId: {}", userId);
Integer pageNo = null;
Integer pageLimit = null;
if (applicationAmendmentPaginationRequestBean.getGlobalFilters() != null) {
@@ -1421,6 +1483,7 @@ public class ApplicationAmendmentRequestDao {
pageableResponseBean.setTotalRecords(entityPage.getTotalElements());
pageableResponseBean.setPageSize(entityPage.getSize());
log.info("Paginated response prepared successfully for userId: {}", userId);
return pageableResponseBean;
}
public Specification<ApplicationAmendmentRequestView> searchPaginationByView(Long userId,ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
@@ -1452,6 +1515,7 @@ public class ApplicationAmendmentRequestDao {
private List<Predicate> getPredicatesByView(ApplicationAmendmentPaginationRequestBean amendmentPaginationRequestBean,
CriteriaBuilder criteriaBuilder, Root<ApplicationAmendmentRequestView> root,Long userId) {
log.info("Building predicates for userId: {}", userId);
Integer year = null;
String search = null;
Map<String, FilterCriteria> filters = new HashMap<>();
@@ -1471,6 +1535,7 @@ public class ApplicationAmendmentRequestDao {
LocalDateTime startOfYear = LocalDateTime.of(filterYear, 1, 1, 0, 0);
LocalDateTime endOfYear = LocalDateTime.of(filterYear, 12, 31, 23, 59, 59);
log.debug("Filtering by year between {} and {}", startOfYear, endOfYear);
// Add the range comparison to filter records within the year
predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), startOfYear, endOfYear));
@@ -1539,8 +1604,111 @@ public class ApplicationAmendmentRequestDao {
applicationAmendmentRequestViewResponse.setExpirationDate(applicationAmendmentRequestView.getExpirationDate());
applicationAmendmentRequestViewResponse.setAssigendUserName(applicationAmendmentRequestView.getAssigendUserName());
applicationAmendmentRequestViewResponse.setStatus(applicationAmendmentRequestView.getStatus());
applicationAmendmentRequestViewResponse.setEmailSendResponse(applicationAmendmentRequestView.getEmailSendResponse());
return applicationAmendmentRequestViewResponse;
}
public ApplicationEvaluationEntity calculateEndDateAndSuspensionDaysOnExpirationOrClosing
(ApplicationEvaluationEntity applicationEvaluationEntity) {
// Fetch all linked amendments
List<ApplicationAmendmentRequestEntity> amendments =
applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(applicationEvaluationEntity.getId());
// Recalculate suspension
long suspendedDays = calculateSuspendedDays(amendments);
// Update end date and save
ApplicationEvaluationEntity oldEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
HubEntity hub = hubService.valdateHub(applicationEvaluationEntity.getAssignedApplicationsEntity().getApplication().getHubId());
Long initialDays = (hub != null) ? hub.getEvaluationExpirationDays() : 30L;
LocalDateTime endDate = applicationEvaluationEntity.getStartDate().plusDays(suspendedDays+initialDays);
applicationEvaluationEntity.setEndDate(endDate);
applicationEvaluationEntity.setSuspendedDays(suspendedDays);
ApplicationEvaluationEntity updated = applicationEvaluationRepository.save(applicationEvaluationEntity);
loggingUtil.addVersionHistory(VersionHistoryRequest.builder()
.request(request)
.actionType(VersionActionTypeEnum.UPDATE)
.oldData(oldEntity)
.newData(updated)
.build());
return updated;
}
public long calculateSuspendedDays(List<ApplicationAmendmentRequestEntity> amendments) {
List<Pair<LocalDateTime, LocalDateTime>> periods = amendments.stream()
.filter(amendmentRequest -> amendmentRequest.getStartDate() != null)
.map(amendmentRequest -> {
LocalDateTime start = amendmentRequest.getStartDate();
LocalDateTime end;
String status = amendmentRequest.getStatus();
if (Boolean.TRUE.equals(ApplicationAmendmentRequestEnum.CLOSE.getValue().equals(status)) && amendmentRequest.getClosingDate() != null) {
end = amendmentRequest.getClosingDate();
} else if (Boolean.TRUE.equals(ApplicationAmendmentRequestEnum.EXPIRED.getValue().equals(status)) && amendmentRequest.getEndDate() != null) {
end = amendmentRequest.getStartDate().plusDays(amendmentRequest.getResponseDays());
}else {
end= amendmentRequest.getEndDate();
}
return Pair.of(start, end);
})
.filter(Objects::nonNull)
.sorted(Comparator.comparing(Pair::getLeft))
.collect(Collectors.toList());
long totalDays = 0;
LocalDateTime currentStart = null;
LocalDateTime currentEnd = null;
for (Pair<LocalDateTime, LocalDateTime> period : periods) {
if (currentStart == null) {
currentStart = period.getLeft();
currentEnd = period.getRight();
} else if (!period.getLeft().isAfter(currentEnd)) {
// Merge overlapping/touching periods
currentEnd = currentEnd.isAfter(period.getRight()) ? currentEnd : period.getRight();
} else {
// Non-overlapping: count previous period
totalDays += ChronoUnit.DAYS.between(currentStart.toLocalDate(), currentEnd.toLocalDate());
currentStart = period.getLeft();
currentEnd = period.getRight();
}
}
if (currentStart != null && currentEnd != null) {
totalDays += ChronoUnit.DAYS.between(currentStart.toLocalDate(), currentEnd.toLocalDate());
}
return totalDays;
}
public ApplicationAmendmentRequestEntity validatApplicationAmendmentRequestByStatus(Long id,String status) {
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalseAndStatus(id, status);
if (applicationAmendmentRequestEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG));
}
return applicationAmendmentRequestEntity;
}
private void saveEmailSendResponse(EmailSendResponse newResponses, ApplicationAmendmentRequestEntity amendment) {
List<EmailSendResponse> mergedResponses = Utils.mergeEmailSendResponses(amendment.getEmailSendResponse(), newResponses);
amendment.setEmailSendResponse(mergedResponses);
applicationAmendmentRequestRepository.save(amendment);
}
public ApplicationAmendmentRequestEntity validatApplicationAmendmentRequestByListStatus(Long id,List<String> status) {
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalseAndStatusIn(id, status);
if (applicationAmendmentRequestEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG));
}
return applicationAmendmentRequestEntity;
}
}

View File

@@ -1,10 +1,15 @@
package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.*;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
@@ -28,15 +33,14 @@ import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.util.*;
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.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.lang3.StringUtils;
import org.h2.util.IOUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -54,17 +58,17 @@ import jakarta.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -74,7 +78,6 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.hibernate.validator.internal.engine.messageinterpolation.el.RootResolver.FORMATTER;
@Component
public class ApplicationDao {
@@ -138,6 +141,9 @@ public class ApplicationDao {
@Value("${call.id}")
private String callId;
@Value("${sviluppumbriaUuid}")
private String sviluppumbriaUuid;
@Autowired
private AmazonS3Service amazonS3Service;
@@ -201,15 +207,28 @@ public class ApplicationDao {
@Autowired
private ApplicationViewRepository applicationViewRepository;
@Autowired
private ApplicationFormViewRepository applicationFormViewRepository;
@Autowired
private FormRepository formRepository;
@Autowired
private ApplicationEvaluationDao applicationEvaluationDao;
public final Random random = new Random();
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
log.info("Starting createApplication: formId={}, applicationId={}", formId, applicationId);
FormEntity formEntity = formService.validateForm(formId);
// callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId);
checkCallEndDate(applicationEntity.getCall());
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
log.info("Validated user-company association for company ID: {}", applicationEntity.getCompanyId());
if(Boolean.FALSE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.DRAFT.getValue()))) {
log.warn("Application ID {} is not in DRAFT status", applicationId);
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
}
formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity);
@@ -236,10 +255,12 @@ public class ApplicationDao {
}
public ApplicationFormEntity createApplicationFormEntity(ApplicationEntity application, FormEntity formEntity) {
log.info("Creating ApplicationFormEntity for applicationId: {}, formId: {}", application.getId(), formEntity.getId());
ApplicationFormEntity applicationFormEntity = new ApplicationFormEntity();
applicationFormEntity.setApplication(application);
applicationFormEntity.setForm(formEntity);
applicationFormEntity = saveApplicationFormEntity(applicationFormEntity);
log.info("Created ApplicationFormEntity with id: {}", applicationFormEntity.getId());
return applicationFormEntity;
}
@@ -291,6 +312,7 @@ public class ApplicationDao {
List<DocumentResponseBean> documentResponseBeans = new ArrayList<>();
if (fileUploadContent.isPresent()) {
String documentId = applicationFormFieldEntity.getFieldValue();
log.debug("Field is file upload/select type. Document IDs: {}", documentId);
if (documentId != null && !documentId.isEmpty()) {
documentResponseBeans = Arrays.stream(documentId.split(","))
.map(String::trim)
@@ -298,6 +320,7 @@ public class ApplicationDao {
.map(docId -> {
DocumentEntity documentEntity = documentService.validateDocument(docId);
if (Boolean.FALSE.equals(DocumentSourceTypeEnum.APPLICATION.getValue().equals(documentEntity.getSource()))) {
log.warn("Document {} source type invalid: {}", docId, documentEntity.getSource());
throw new CustomValidationException(Status.NOT_FOUND,Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
}
return documentEntity;
@@ -323,6 +346,7 @@ public class ApplicationDao {
ApplicationEntity applicationEntity= validateApplication(id);
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.DRAFT.getValue().equals(applicationEntity.getStatus()))) {
log.warn("Application with ID: {} is not in DRAFT status, cannot delete. Current status: {}", id, applicationEntity.getStatus());
throw new CustomValidationException(
Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS)
@@ -333,6 +357,7 @@ public class ApplicationDao {
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
applicationEntity.setIsDeleted(true);
applicationEntity = applicationRepository.save(applicationEntity);
log.info("Marked application as deleted and saved for ID: {}", id);
/** This code is responsible for adding a version history log for the "Delete application" operation. **/
loggingUtil.addVersionHistory(
@@ -420,6 +445,7 @@ public class ApplicationDao {
}
private ApplicationResponse getApplicationResponse(ApplicationEntity applicationEntity) {
log.info("Generating ApplicationResponse for application ID: {}", applicationEntity.getId());
ApplicationResponse responseBean = new ApplicationResponse();
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalFormSteps = flowFormDao.calculateTotalSteps(flowEdgesList);
@@ -460,9 +486,13 @@ public class ApplicationDao {
}
public ApplicationEntity validateApplication(Long id) {
log.info("Validating existence of Application with ID: {}", id);
ApplicationEntity applicationEntity = applicationRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
.orElseThrow(() -> {
log.warn("Application not found for ID: {}", id);
return new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG));
});
return applicationEntity;
}
@@ -486,10 +516,12 @@ public class ApplicationDao {
}
private ApplicationFormEntity getApplicationFormOrCreate(FormEntity formEntity, ApplicationEntity applicationEntity) {
log.info("Fetching ApplicationForm for Application ID: {} and Form ID: {}", applicationEntity.getId(), formEntity.getId());
ApplicationFormEntity applicationFormEntity = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), formEntity.getId());
ApplicationFormEntity oldApplicationFormEntity = Utils.getClonedEntityForData(applicationFormEntity);
if (applicationFormEntity == null) {
log.info("No existing ApplicationForm found. Creating new ApplicationForm for Application ID: {}, Form ID: {}", applicationEntity.getId(), formEntity.getId());
applicationFormEntity = createApplicationFormEntity(applicationEntity, formEntity);
/** This code is responsible for adding a version history log for the "Create application form" operation. **/
@@ -515,6 +547,8 @@ public class ApplicationDao {
public ApplicationFormFieldEntity createOrUpdateApplicationFormField(ApplicationFormFieldRequestBean applicationFormFieldRequestBean,
ApplicationFormEntity applicationFormEntity, List<ApplicationFormFieldEntity> applicationFormFieldEntities, FormEntity formEntity,FieldValidator fieldValidator) {
log.info("Starting createOrUpdateApplicationFormField for ApplicationForm ID: {}", applicationFormEntity.getId());
ApplicationFormFieldEntity applicationFormFieldEntity = new ApplicationFormFieldEntity();
List<Long> newDocumentIds = validateFileUploadDocuments(applicationFormFieldRequestBean, formEntity);
@@ -534,7 +568,9 @@ public class ApplicationDao {
try {
BigDecimal amountRequested = new BigDecimal(fieldValue.toString());
applicationFormEntity.getApplication().setAmountRequested(amountRequested);
log.info("Set amountRequested to {} for Application ID: {}", amountRequested, applicationFormEntity.getApplication().getId());
} catch (NumberFormatException e) {
log.error("Invalid number format for requested amount: {}", fieldValue, e);
throw new IllegalArgumentException("Field value is not a valid number: " + fieldValue, e);
}
}
@@ -675,6 +711,8 @@ public class ApplicationDao {
List<Long> documentIds=null;
// List<ContentResponseBean> contentResponseBeans=Utils.convertJsonStringToList(formEntity.getContent(),ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans=formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
log.debug("Validating file upload documents for field ID: {} in form ID: {}", applicationFormFieldRequestBean.getFieldId(), formEntity.getId());
for (ContentResponseBean contentResponseBean:contentResponseBeans){
if(Boolean.TRUE.equals(contentResponseBean.getName().equals("fileupload")) || Boolean.TRUE.equals(contentResponseBean.getName().equals("fileselect"))) {
if (contentResponseBean.getId().equals(applicationFormFieldRequestBean.getFieldId())) {
@@ -684,6 +722,7 @@ public class ApplicationDao {
String documentId = (String) fieldValueObject;
// Now you can use documentId as needed
documentIds = validateDocumentIds(documentId);
log.info("Validated document IDs: {}", documentIds);
}
}
}
@@ -693,6 +732,7 @@ public class ApplicationDao {
public List<Long> validateDocumentIds(String documentId) {
if (documentId != null && !documentId.isEmpty()) {
log.info("Validating document IDs: {}", documentId);
return Arrays.stream(documentId.split(","))
.map(Long::parseLong)
.peek(docId -> documentService.validateDocument(docId))
@@ -745,6 +785,7 @@ public class ApplicationDao {
}
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId, Long formId) {
log.info("Received request to get application by formId. ApplicationId: {}, FormId: {}", applicationId, formId);
List<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
List<FormEntity> formEntities = new ArrayList<>();
UserEntity userEntity = validator.validateUser(request);
@@ -895,6 +936,7 @@ public class ApplicationDao {
public ApplicationResponse createApplicationByCallId(CompanyEntity companyEntity,
ApplicationRequest applicationRequest, Long callId, UserEntity userEntity) {
log.info("Start creating application for CallId: {}, UserId: {}, CompanyId: {}", callId, userEntity.getId(), companyEntity.getId());
CallEntity call = callService.validateCall(callId);
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyEntity.getId());
checkCallEndDate(call);
@@ -918,39 +960,63 @@ public class ApplicationDao {
public void checkIfApplicationExists(CallEntity call, UserWithCompanyEntity userWithCompanyEntity, UserEntity userEntity){
log.info("Checking existing applications for UserId: {}, UserWithCompanyId: {}, CallId: {}",
userEntity.getId(), userWithCompanyEntity.getId(), call.getId());
List<ApplicationEntity> applications = applicationRepository.findByUserIdAndUserWithCompany_IdAndCall_IdAndIsDeletedFalseAndStatusNot(
userEntity.getId(), userWithCompanyEntity.getId(), call.getId(), ApplicationStatusTypeEnum.REJECTED.name()
);
if (!applications.isEmpty()) {
log.warn("Application already exists for UserId: {}, UserWithCompanyId: {}, CallId: {}. Applications found: {}",
userEntity.getId(), userWithCompanyEntity.getId(), call.getId(), applications.size());
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
}
}
public String generateRandomFiveDigitNumber() {
int number = 10000 + random.nextInt(90000); // Generates a number from 10000 to 99999
return String.valueOf(number);
}
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
log.info("Updating status for Application id : " + applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
checkCallEndDate(applicationEntity.getCall());
log.info("Call end date verified successfully | callId: {}", applicationEntity.getCall().getId());
//cloned entity for old application data
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(applicationEntity);
HubEntity hub=hubService.valdateHub(applicationEntity.getHubId());
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
log.warn("Attempt to change status after submission denied | applicationId: {}", applicationId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
}
if (Boolean.TRUE.equals(applicationEntity.getStatus().equals(status.getValue()))) {
log.warn("Requested status is the same as current status | applicationId: {}, status: {}", applicationId, status);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_IN_PREVIOUS_STATUS));
}
if (status.equals(ApplicationStatusTypeEnum.APPOINTMENT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.NDG.getValue()))){
String appointmentId = generateRandomFiveDigitNumber();
applicationEntity.setAppointmentId(appointmentId);
applicationEntity.setStatus(ApplicationStatusTypeEnum.APPOINTMENT.getValue());
}
if (status.equals(ApplicationStatusTypeEnum.SUBMIT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
// callService.validatePublishedCall(applicationEntity.getCall().getId(), userEntity.getHub().getId());
checkCallEndDate(applicationEntity.getCall());
Long protocolNumber = protocolDao.getProtocolNumber(userEntity.getHub());
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true);
protocolDao.saveProtocolEntity(protocolEntity);
applicationEntity.setProtocol(protocolEntity);
if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(sviluppumbriaUuid))) {
protocolEntity = protocolDao.createExternalProtocol(applicationEntity, company, protocolEntity);
}
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(protocolEntity.getCreatedDate());
applicationEntity = applicationRepository.save(applicationEntity);
@@ -961,16 +1027,18 @@ public class ApplicationDao {
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEntity).newData(applicationEntity).build());
sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailToUserAndCompany(userEntity, applicationEntity,company);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
applicationEntity.setStatus(status.getValue());
log.info("Status updated to SUBMIT for applicationId: " + applicationId);
}
if (status.equals(ApplicationStatusTypeEnum.DRAFT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.AWAITING.getValue()))) {
checkCallEndDate(applicationEntity.getCall());
applicationEntity.setStatus(status.getValue());
log.info("Status updated to DRAFT for applicationId: " + applicationId);
}
if (status.equals(ApplicationStatusTypeEnum.AWAITING) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
checkCallEndDate(applicationEntity.getCall());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository.findByApplicationIdAndStatus(applicationId,
ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
deleteSignedDocumentFromS3(applicationSignedDocument);
@@ -1072,9 +1140,9 @@ public class ApplicationDao {
}
}
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity) {
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity,CompanyEntity company) {
log.info("Preparing to send submission email | applicationId: {}, userId: {}", applicationEntity.getId(), userEntity.getId());
CallEntity call =applicationEntity.getCall();
CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId());
ProtocolEntity protocol= applicationEntity.getProtocol();
HubEntity hub = hubService.valdateHub(applicationEntity.getHubId());
@@ -1102,7 +1170,7 @@ public class ApplicationDao {
if (userEntity.getBeneficiary() != null) {
emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY);
email = userEntity.getBeneficiary().getEmail();
emailLogRequest.setUserId(userEntity.getBeneficiary().getId());
emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId());
}
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogRequest);
List<String> recipientEmails = new ArrayList<>();
@@ -1151,24 +1219,6 @@ public class ApplicationDao {
EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId());
// mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
// mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
// mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
// if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(defaultHubUuid))) {
// if (validator.isProductionProfileActivated()) {
// emailLogRequest.setRecipientEmails(carloEmail);
//// mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
// emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(carloEmail),emailLogRequest);
// }
// List<String> listDefaultSystemReceiverEmail = Arrays.stream(defaultSystemReceiverEmail.split(","))
// .map(String::trim)
// .filter(email -> !email.isEmpty())
// .toList();
//
// emailLogRequest.setRecipientEmails(defaultSystemReceiverEmail);
// emailNotificationDao.sendMail(hub.getId(), subject, body, listDefaultSystemReceiverEmail, emailLogRequest);
// }
List<String> hubEmails = Arrays.stream(hub.getEmail().split(","))
.map(String::trim)
.filter(email -> !email.isEmpty())
@@ -1181,6 +1231,7 @@ public class ApplicationDao {
}
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,
MultipartFile file) {
log.info("Received request to upload signed document | applicationId: {}, fileName: {}", applicationId, file.getOriginalFilename());
ApplicationEntity applicationEntity = validateApplication(applicationId);
checkCallEndDate(applicationEntity.getCall());
//cloned entity for old data
@@ -1193,14 +1244,23 @@ public class ApplicationDao {
ApplicationSignedDocumentEntity oldApplicationSingedDocumentData = Utils.getClonedEntityForData(applicationSignedDocument);
if (applicationSignedDocument != null) {
log.info("Existing active signed document found and will be deleted | applicationId: {}, fileName: {}", applicationId, applicationSignedDocument.getFileName());
deleteSignedDocumentFromS3(applicationSignedDocument);
}
String hash ="";
try {
hash = FileHashUtil.calculateSHA256(file.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = uploadFileOnAmazonS3ForUserSignedDocument(file, applicationEntity.getCall().getId(), applicationId);
log.info("File uploaded to S3 successfully | applicationId: {}", applicationId);
applicationSignedDocument = new ApplicationSignedDocumentEntity();
applicationSignedDocument.setApplication(applicationEntity);
applicationSignedDocument.setFileName(uploadFileOnAmazonS3.getFileName());
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
applicationSignedDocument.setFileHash(hash);
applicationSignedDocument = applicationSignedDocumentRepository.save(applicationSignedDocument);
/** This code is responsible for adding a version history log for the "assign application document" operation. **/
@@ -1209,6 +1269,8 @@ public class ApplicationDao {
applicationEntity.setStatus(ApplicationStatusTypeEnum.READY.getValue());
applicationEntity = applicationRepository.save(applicationEntity);
log.info("Application status updated to READY | applicationId: {}", applicationEntity.getId());
/** This code is responsible for adding a version history log for the "Create Call" operation. **/
loggingUtil.addVersionHistory(
@@ -1217,16 +1279,22 @@ public class ApplicationDao {
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
public void deleteSignedDocumentFromS3(ApplicationSignedDocumentEntity applicationSignedDocumentEntity){
log.info("Starting soft delete of signed document | applicationSignedDocumentId: {}, fileName: {}",
applicationSignedDocumentEntity.getId(), applicationSignedDocumentEntity.getFileName());
ApplicationSignedDocumentEntity oldApplicationSignedDocument = Utils.getClonedEntityForData(applicationSignedDocumentEntity);
String oldS3Path = applicationSignedDocumentEntity.getFilePath();
log.debug("Old S3 path: {} ", oldS3Path);
String newS3Path = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.DELETED_USER_SIGNED_DOCUMENT,applicationSignedDocumentEntity.getApplication().getCall().getId(),applicationSignedDocumentEntity.getApplication().getId(),0L);
log.debug("Generated new S3 path for deleted document: {}", newS3Path);
UploadFileOnAmazonS3Response response = amazonS3Service.moveFile(applicationSignedDocumentEntity.getFileName(), oldS3Path, newS3Path);
log.info("Moved file in S3 from {} to {} | fileName: {}", oldS3Path, newS3Path, response.getFileName());
applicationSignedDocumentEntity.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentEntity.setFileName(response.getFileName());
applicationSignedDocumentEntity.setFilePath(response.getFilePath());
applicationSignedDocumentRepository.save(applicationSignedDocumentEntity);
log.info("Updated signed document entity status to INACTIVE and saved | applicationSignedDocumentId: {}", applicationSignedDocumentEntity.getId());
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldApplicationSignedDocument).newData(applicationSignedDocumentEntity).build());
}
@@ -1245,6 +1313,7 @@ public class ApplicationDao {
log.info("S3 Path {}", s3Path);
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
} catch (Exception e) {
log.error("Failed to upload user signed document | callId: {}, applicationId: {}, error: {}", callId, applicationId, e.getMessage(), e);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
}
@@ -1252,6 +1321,7 @@ public class ApplicationDao {
try {
return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId,0L);
} catch (IllegalArgumentException e) {
log.error("Failed to generate S3 path for delegation | callId: {}, applicationId: {}, error: {}", callId, applicationId, e.getMessage(), e);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
}
}
@@ -1266,6 +1336,7 @@ public class ApplicationDao {
.setStatus(ApplicationSignedDocumentStatusEnum.valueOf(applicationSignedDocument.getStatus()));
applicationSignedDocumentResponse.setCreatedDate(applicationSignedDocument.getCreatedDate());
applicationSignedDocumentResponse.setUpdatedDate(applicationSignedDocument.getUpdatedDate());
applicationSignedDocumentResponse.setFileHash(applicationSignedDocument.getFileHash());
return applicationSignedDocumentResponse;
}
@@ -1276,13 +1347,14 @@ public class ApplicationDao {
}
String filename = file.getOriginalFilename();
if (filename == null || !filename.endsWith(".p7m")) {
log.warn("Invalid file type detected | filename: {}", filename);
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_INVALIDTYPE));
}
}
public ApplicationSignedDocumentResponse getSignedDocument(HttpServletRequest request, Long applicationId) {
log.info("Fetching signed document for applicationId: {}", applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
// validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
@@ -1296,6 +1368,7 @@ public class ApplicationDao {
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
log.warn("No active signed document found for applicationId: {}", applicationId);
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
@@ -1303,6 +1376,7 @@ public class ApplicationDao {
}
public void deleteSignedDocument(HttpServletRequest request, Long applicationId) {
log.info("Initiating deletion of signed document for applicationId: {}", applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
@@ -1311,6 +1385,7 @@ public class ApplicationDao {
//cloned entity for old data
ApplicationSignedDocumentEntity oldApplicationSignedDocument = Utils.getClonedEntityForData(applicationSignedDocument);
if(applicationSignedDocument == null) {
log.warn("No active signed document found to delete for applicationId: {}", applicationId);
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
@@ -1323,7 +1398,7 @@ public class ApplicationDao {
}
public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId) {
log.info("Starting application validation process | applicationId: {}", applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(applicationEntity);
checkCallEndDate(applicationEntity.getCall());
@@ -1331,15 +1406,18 @@ public class ApplicationDao {
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.DRAFT.getValue().equals(applicationEntity.getStatus()))) {
log.warn("Application not in draft status | applicationId: {}, status: {}", applicationId, applicationEntity.getStatus());
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
}
if (applicationEntity.getAmountRequested() == null || applicationEntity.getAmountRequested().compareTo(BigDecimal.ZERO) <= 0 ) {
log.warn("Invalid amount requested | amount: {}", applicationEntity.getAmountRequested());
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.AMOUNT_REQUEST_SHOULD_GREATED_THEN_ZERO));
}
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalSteps = flowFormDao.calculateTotalSteps(flowEdgesList);
Integer completedSteps = flowFormDao.getCompletedSteps(applicationEntity, true);
if (totalSteps.intValue() != completedSteps) {
log.warn("Application incomplete | applicationId: {}", applicationId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
@@ -1354,7 +1432,7 @@ public class ApplicationDao {
}
public byte[] downloadApplicationDocumentsAsZip(HttpServletRequest request, Long applicationId) {
log.info("Starting ZIP download process for applicationId: {}", applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
validateAssignedUser(request, applicationId);
Set<Long> documentIds = extractDocumentIdsFromApplicationForms(applicationId);
@@ -1364,13 +1442,14 @@ public class ApplicationDao {
List<DocumentEntity> amendmentDocuments = fetchAmendmentDocuments(applicationId);
List<DocumentEntity> evaluationDocuments = fetchEvaluationDocuments(applicationId);
if (documents.isEmpty() && signedDocument == null && amendmentDocuments.isEmpty() && evaluationDocuments.isEmpty()) {
log.warn("No documents found for applicationId: {}", applicationId);
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
}
return createZipWithDocuments(applicationEntity, documents, signedDocument, amendmentDocuments, evaluationDocuments, applicationId);
}
private void validateAssignedUser(HttpServletRequest request, Long applicationId) {
log.info("Validating assigned user for applicationId: {}", applicationId);
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
if (assignedApplications != null) {
validator.validatePreInstructor(request, assignedApplications.getUserId());
@@ -1378,7 +1457,7 @@ public class ApplicationDao {
}
private Set<Long> extractDocumentIdsFromApplicationForms(Long applicationId) {
log.info("Extracting document IDs from application forms | applicationId: {}", applicationId);
Set<Long> documentIds = new HashSet<>();
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationId);
applicationForms.forEach(applicationForm -> {
@@ -1400,16 +1479,17 @@ public class ApplicationDao {
}
private List<DocumentEntity> fetchAmendmentDocuments(Long applicationId) {
log.info("Fetching amendment documents for applicationId: {}", 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) {
log.info("Fetching evaluation documents for applicationId: {}", applicationId);
Optional<ApplicationEvaluationEntity> evaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
if (evaluationEntity.isPresent()) {
Long evaluationId = evaluationEntity.get().getId();
log.debug("Found evaluation entity with id: {}", evaluationId);
return documentRepository.findBySourceIdInAndSourceAndIsDeletedFalse(Collections.singleton(evaluationId), DocumentSourceTypeEnum.EVALUATION.getValue());
}
return Collections.emptyList();
@@ -1423,12 +1503,14 @@ public class ApplicationDao {
return "unknown";
}
private void addDocumentToZip(ZipOutputStream zos, String s3Folder, String filePath, String fullPath) {
log.info("Attempting to add file to ZIP. S3 folder: {}, file path: {}", s3Folder, filePath);
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, filePath)) {
zos.putNextEntry(new ZipEntry(fullPath));
IOUtils.copy(fileInputStream, zos);
zos.closeEntry();
} catch (IOException e) {
log.error("Failed to add file to ZIP. S3 folder: {}, file path: {}, error: {}",
s3Folder, filePath, e.getMessage(), e);
throw new RuntimeException("Error downloading or adding document to ZIP: " + fullPath, e);
}
}
@@ -1833,4 +1915,429 @@ public class ApplicationDao {
responseBean.setDateRejected(applicationView.getDateRejected());
return responseBean;
}
public List<ApplicationFormView> getApplicationFormData(Long callId) {
List<ApplicationFormView> applicationFormViews=new ArrayList<>();
applicationFormViews= applicationFormViewRepository.findByCallId(callId);
return applicationFormViews;
}
private List<Method> getStaticGetterMethods() {
List<String> excluded = Arrays.asList(
GepafinConstant.GET_FIELD_TYPE,GepafinConstant.GET_APPLICATION_FORM_ID,GepafinConstant.GET_ID,GepafinConstant.GET_CLASS,GepafinConstant.GET_FORM_ID,GepafinConstant.GET_FIELD_ID,GepafinConstant.GET_FIELD_LABEL,GepafinConstant.GET_FIELD_VALUE,GepafinConstant.GET_REPORT_HEADER,GepafinConstant.GET_REPORT_ENABLE
);
Method applicationIdMethod = null;
List<Method> methods = new ArrayList<>();
for (Method m : ApplicationFormView.class.getMethods()) {
if (m.getName().equals(GepafinConstant.GET_APPLICATION_ID)) {
applicationIdMethod = m;
} else if (m.getName().startsWith(GepafinConstant.GET) && m.getParameterCount() == 0 && !excluded.contains(m.getName())) {
methods.add(m);
}
}
methods.sort(Comparator.comparing(Method::getName)); // Sort remaining
if (applicationIdMethod != null) {
methods.add(0, applicationIdMethod); // Add it to the beginning
}
return methods;
}
private String methodToHeader(Method method) {
String name = method.getName().substring(3); // strip "get"
return Arrays.stream(name.split("(?=[A-Z])"))
.map(String::toLowerCase)
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
}
private String invokeGetter(ApplicationFormView view, Method method) {
try {
Object value = method.invoke(view);
if (value == null) return "";
String stringValue;
if (value instanceof LocalDate) {
stringValue = ((LocalDate) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} else if (value instanceof LocalDateTime) {
stringValue = ((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} else if (value instanceof Date) {
stringValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
} else {
stringValue = value.toString();
}
// Wrap it in ="..." to make Excel treat it as a literal string
return "=\"" + stringValue.replace("\"", "\"\"") + "\"";
} catch (Exception e) {
return "";
}
}
public byte[] exportCsv(Long callId) {
List<ApplicationFormView> results = getApplicationFormData(callId);
Map<Long, ApplicationFormView> appInfo = new HashMap<>();
Map<Long, Map<String, String>> appFieldValues = new LinkedHashMap<>();
Set<String> tableFieldIds = new HashSet<>();
Map<String, String> fieldIdToLabel = new LinkedHashMap<>();
for (ApplicationFormView row : results) {
appInfo.putIfAbsent(row.getApplicationId(), row);
String label=row.getReportHeader();
if(Boolean.TRUE.equals(StringUtils.isEmpty(label))){
label=row.getFieldLabel();
}
fieldIdToLabel.putIfAbsent(row.getFieldId(), label);
if (GepafinConstant.TABLE.equalsIgnoreCase(row.getFieldType())) {
tableFieldIds.add(row.getFieldId());
continue;
}
String value = Optional.ofNullable(row.getFieldValue())
.map(v -> v.startsWith("\"") && v.endsWith("\"") ? v.substring(1, v.length() - 1) : v)
.orElse("");
appFieldValues
.computeIfAbsent(row.getApplicationId(), k -> new LinkedHashMap<>())
.merge(row.getFieldId(), value, (v1, v2) -> v1.equals(v2) ? v1 : String.join(", ", v1, v2));
}
Map<String, List<String>> tableHeadersByFieldId = new LinkedHashMap<>();
Map<Long, Map<String, String>> tableDataByApp = new HashMap<>();
prepareTableFieldData(results, tableFieldIds, tableHeadersByFieldId, tableDataByApp);
// Final header construction
List<Method> staticMethods = getStaticGetterMethods();
List<String> staticHeaders = staticMethods.stream().map(this::methodToHeader).toList();
List<String> dynamicHeaders = new ArrayList<>();
for (String fieldId : fieldIdToLabel.keySet()) {
if (tableHeadersByFieldId.containsKey(fieldId)) {
dynamicHeaders.addAll(tableHeadersByFieldId.get(fieldId));
} else {
dynamicHeaders.add(fieldIdToLabel.get(fieldId));
}
}
List<String> allHeaders = new ArrayList<>(staticHeaders);
allHeaders.addAll(dynamicHeaders);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(out), CSVFormat.DEFAULT.withHeader(allHeaders.toArray(new String[0])))) {
for (Long appId : appFieldValues.keySet()) {
ApplicationFormView appRow = appInfo.get(appId);
Map<String, String> flatFieldVals = appFieldValues.get(appId);
Map<String, String> tableVals = tableDataByApp.getOrDefault(appId, Collections.emptyMap());
List<String> row = new ArrayList<>();
for (Method method : staticMethods) {
row.add(invokeGetter(appRow, method));
}
for (String fieldId : fieldIdToLabel.keySet()) {
if (tableHeadersByFieldId.containsKey(fieldId)) {
for (String header : tableHeadersByFieldId.get(fieldId)) {
row.add(tableVals.getOrDefault(header, ""));
}
} else {
row.add(flatFieldVals.getOrDefault(fieldId, ""));
}
}
printer.printRecord(row);
}
} catch (IOException e) {
throw new RuntimeException("CSV generation failed", e);
}
return out.toByteArray();
}
private Map<String, String> extractTableData(String fieldType,
ContentResponseBean content, String fieldValue) {
if (content == null) return Map.of();
Map<String, String> result = new LinkedHashMap<>();
List<Map<String, Object>> rows = null;
try {
rows = GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(fieldType)
? Utils.convertJsonToListMap(String.valueOf(PdfUtils.extractRows(fieldValue)))
: Utils.convertJsonToListMap(fieldValue);
} catch (Exception e) {
throw new RuntimeException(e);
}
Map<String, String> fieldLabelMap = new LinkedHashMap<>();
Set<String> predefinedIds = new LinkedHashSet<>();
Set<String> dynamicIds = new LinkedHashSet<>();
Set<String> numericFormulaIds = new LinkedHashSet<>();
for (SettingResponseBean setting : content.getSettings()) {
String settingName = setting.getName();
if(settingName.equals(GepafinConstant.REPORT_ENABLE)){
Boolean enable= (Boolean) setting.getValue();
if(Boolean.FALSE.equals(enable)){
return null;
}
}
if (Boolean.TRUE.equals(GepafinConstant.TABLE_COLUMNS.equals(settingName)) || Boolean.TRUE.equals(GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(settingName))) {
Map<String, Object> valueMap = (Map<String, Object>) setting.getValue();
if (valueMap == null) continue;
List<Map<String, Object>> columns = (List<Map<String, Object>>) valueMap.get(GepafinConstant.STATE_FIELD_DATA);
if (columns != null) {
for (Map<String, Object> col : columns) {
String id = String.valueOf(col.get(GepafinConstant.NAME));
if (Boolean.FALSE.equals(col.get(GepafinConstant.PREDEFINED))) {
if (GepafinConstant.NUMERIC.equals(col.get(GepafinConstant.FIELD_TYPE)) && Boolean.TRUE.equals(col.get(GepafinConstant.ENABLE_FORMULA))) {
numericFormulaIds.add(id);
}
}
}
}
}
if (Boolean.TRUE.equals(GepafinConstant.REPORT_COLUMNS.equals(settingName))) {
List<Map<String, Object>> reportColumns = (List<Map<String, Object>>) setting.getValue();
if (reportColumns != null) {
for (Map<String, Object> col : reportColumns) {
Boolean enableCsv = (Boolean) col.get(GepafinConstant.EBABLE_CSV);
if (Boolean.TRUE.equals(enableCsv)) {
String id = String.valueOf(col.get(GepafinConstant.NAME));
String fieldCsvLabel = col.get(GepafinConstant.LABEL_CSV) != null
? String.valueOf(col.get(GepafinConstant.LABEL_CSV))
: String.valueOf(col.get(GepafinConstant.LABEL));
fieldLabelMap.put(id, fieldCsvLabel);
if (Boolean.TRUE.equals(col.get(GepafinConstant.PREDEFINED))) {
predefinedIds.add(id);
} else {
dynamicIds.add(id);
}
}
}
}
}
}
if (predefinedIds.isEmpty()) {
return null;
}
for (Map<String, Object> row : rows) {
String prefix = predefinedIds.stream()
.map(id -> String.valueOf(row.getOrDefault(id, "")))
.filter(s -> !s.isBlank())
.findFirst().orElse("");
for (String dynId : dynamicIds) {
String dynLabel = fieldLabelMap.get(dynId);
for (String preId : predefinedIds.isEmpty() ? List.of("") : predefinedIds) {
String preLabel = fieldLabelMap.get(preId);
String key = dynLabel + " " + (preLabel != null ? preLabel + " " : "") + prefix;
result.put(key, String.valueOf(row.getOrDefault(dynId, "")));
}
}
}
// Add totals for numeric formula-enabled columns
for (String dynId : numericFormulaIds) {
double sum = rows.stream()
.mapToDouble(r -> {
try {
return Double.parseDouble(String.valueOf(r.getOrDefault(dynId, "0")));
} catch (NumberFormatException e) {
return 0.0;
}
}).sum();
String dynLabel = fieldLabelMap.get(dynId);
result.put("TOTAL " + dynLabel, String.valueOf(sum));
}
return result;
}
private void prepareTableFieldData(
List<ApplicationFormView> results,
Set<String> tableFieldIds,
Map<String, List<String>> tableHeadersByFieldId,
Map<Long, Map<String, String>> tableDataByApp) {
if (tableFieldIds.isEmpty()) return;
Map<Long, List<ApplicationFormView>> groupedByApp = results.stream()
.filter(r -> tableFieldIds.contains(r.getFieldId()))
.collect(Collectors.groupingBy(ApplicationFormView::getApplicationId));
for (Map.Entry<Long, List<ApplicationFormView>> entry : groupedByApp.entrySet()) {
Long appId = entry.getKey();
Map<String, String> flattenedAll = new LinkedHashMap<>();
for (ApplicationFormView row : entry.getValue()) {
formRepository.findById(row.getFormId()).ifPresent(form -> {
List<ContentResponseBean> contentList = Utils.convertJsonStringToList(form.getContent(), ContentResponseBean.class);
ContentResponseBean content = contentList.stream()
.filter(c -> c.getId().equals(row.getFieldId()))
.findFirst()
.orElse(null);
if (content == null) return;
content.getSettings().stream()
.filter(setting -> GepafinConstant.TABLE_COLUMNS.equals(setting.getName())
|| GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(setting.getName()))
.findFirst()
.ifPresent(setting -> {
Map<String, String> flattened = extractTableData(
row.getFieldType(),
content,
row.getFieldValue()
);
if (flattened != null) {
tableHeadersByFieldId.putIfAbsent(row.getFieldId(), new ArrayList<>(flattened.keySet()));
flattenedAll.putAll(flattened);
}
});
});
}
tableDataByApp.put(appId, flattenedAll);
}
}
public ApplicationResponse readmitApplication(HttpServletRequest request, Long applicationId) {
log.info("Re-admiting the Application with id : {}", applicationId);
ApplicationEntity applicationEntity = fetchRejectedApplication(applicationId);
if(applicationEntity == null){
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG));
}
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId())
.ifPresent(assignedApp -> processAssignedAppAndEvaluation(request, applicationEntity, assignedApp));
return getApplicationResponse(applicationEntity);
}
private ApplicationEntity fetchRejectedApplication(Long applicationId) {
return applicationRepository.findByIdAndStatusAndIsDeletedFalse(applicationId, ApplicationStatusTypeEnum.REJECTED.getValue());
}
private void processAssignedAppAndEvaluation(HttpServletRequest request, ApplicationEntity applicationEntity, AssignedApplicationsEntity assignedApp) {
applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApp.getId())
.ifPresent(eval -> reopenApplication(request, applicationEntity, assignedApp, eval));
}
private void reopenApplication(HttpServletRequest request, ApplicationEntity applicationEntity,
AssignedApplicationsEntity assignedApp, ApplicationEvaluationEntity evaluationEntity) {
ApplicationEntity oldApplication = Utils.getClonedEntityForData(applicationEntity);
AssignedApplicationsEntity oldAssignedApp = Utils.getClonedEntityForData(assignedApp);
ApplicationEvaluationEntity oldEvaluation = Utils.getClonedEntityForData(evaluationEntity);
updateApplicationStatus(applicationEntity);
updateAssignedApplicationStatus(assignedApp);
updateEvaluationEntity(applicationEntity.getHubId(), evaluationEntity);
saveEntities(applicationEntity, assignedApp, evaluationEntity);
/** This code is responsible for adding a version history log for the "Update Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplication).newData(applicationEntity).build());
/** 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(oldEvaluation).newData(evaluationEntity).build());
/** 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(oldAssignedApp).newData(assignedApp).build());
}
private void updateApplicationStatus(ApplicationEntity applicationEntity) {
applicationEntity.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
applicationEntity.setDateRejected(null);
}
private void updateAssignedApplicationStatus(AssignedApplicationsEntity assignedApp) {
assignedApp.setStatus(AssignedApplicationEnum.OPEN.getValue());
}
private void updateEvaluationEntity(Long hubId, ApplicationEvaluationEntity evaluationEntity) {
HubEntity hub = hubService.valdateHub(hubId);
Long evaluationDays = (hub != null) ? hub.getEvaluationExpirationDays() : 30L;
LocalDateTime now = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
evaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
evaluationEntity.setClosingDate(null);
evaluationEntity.setActiveDays(null);
evaluationEntity.setEndDate(now.plusDays(evaluationDays));
evaluationEntity.setStartDate(now);
evaluationEntity.setRemainingDays(evaluationDays);
evaluationEntity.setSuspendedDays(0L);
evaluationEntity.setStopDateTime(null);
}
private void saveEntities(ApplicationEntity app, AssignedApplicationsEntity assignedApp, ApplicationEvaluationEntity eval) {
applicationRepository.save(app);
assignedApplicationsRepository.save(assignedApp);
applicationEvaluationRepository.save(eval);
}
public void sendApplicationSubmissionFailureEmail(EmailLogRequest emailLogRequest){
Long callId = emailLogRequest.getCallId();
CallEntity call = callService.validateCall(callId);
HubEntity hub = call.getHub();
Long userId = emailLogRequest.getUserId();
UserEntity user = userService.validateUser(userId);
Long applicationId = emailLogRequest.getApplicatioId();
ApplicationEntity applicationEntity = validateApplication(applicationId);
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_FAILURE_NOTIFICATION,
hub, null);
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{scenario}}",emailLogRequest.getEmailType().getValue());
bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{application_id}}", applicationEntity.getId().toString());
bodyPlaceholders.put("{{company_name}}", company.getCompanyName());
bodyPlaceholders.put("{{protocol_number}}", applicationEntity.getProtocol().getProtocolNumber().toString());
bodyPlaceholders.put("{{user_action_id}}",emailLogRequest.getUserActionId().toString());
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,user.getEmail(),user.getId(),applicationEntity.getId(),null,callId);
emailLogRequest.setRecipientEmails(GepafinConstant.RINALDO_EMAIL);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(GepafinConstant.RINALDO_EMAIL),emailLogRequest);
}
}

View File

@@ -143,6 +143,9 @@ public class ApplicationEvaluationDao {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private EmailDao emailDao;
private ApplicationEvaluationEntity convertToEntity(UserEntity user, ApplicationEvaluationRequest req, Long assignedApplciationId) {
@@ -311,7 +314,6 @@ public class ApplicationEvaluationDao {
response.setUpdatedDate(entity.getUpdatedDate());
response.setNumberOfCheck(entity.getAssignedApplicationsEntity().getApplication().getCall().getNumberOfCheck());
response.setAppointmentTemplateId(entity.getAssignedApplicationsEntity().getApplication().getCall().getAppointmentTemplateId());
}
@@ -653,6 +655,7 @@ public class ApplicationEvaluationDao {
ApplicationEvaluationRequest req,
Long assignedApplicationId) {
log.info("Start createOrUpdateApplicationEvaluation: assignedApplicationId={}, userId={}", assignedApplicationId, user.getId());
Optional<ApplicationEvaluationEntity> existingEntityOptional =
applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId);
ApplicationEvaluationEntity entity = null;
@@ -663,6 +666,7 @@ public class ApplicationEvaluationDao {
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
validateApplicationEvaluationRequest(req, application);
if (existingEntityOptional.isPresent()) {
log.info("Updating existing application evaluation for assignedApplicationId={}", assignedApplicationId);
entity = existingEntityOptional.get();
oldApplicationEvaluation = Utils.getClonedEntityForData(entity);
if(req.getCriteria()!=null) {
@@ -688,6 +692,7 @@ public class ApplicationEvaluationDao {
entity = applicationEvaluationRepository.save(entity);
} else {
log.info("Creating new application evaluation for assignedApplicationId={}", assignedApplicationId);
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsService.validateAssignedApplication(assignedApplicationId);
entity = convertToEntity(user, req, assignedApplicationId);
actionType = VersionActionTypeEnum.INSERT;
@@ -701,7 +706,11 @@ public class ApplicationEvaluationDao {
/** This code is responsible for adding a version history log for the "Update Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplication).newData(application).build());
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_CREATION);
// Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_CREATION);
Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("{{call_name}}", application.getCall().getName());
placeHolders.put("{{protocol_number}}", String.valueOf(application.getProtocol().getProtocolNumber()));
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_CREATION);
notificationDao.sendNotificationToInstructor(placeHolders,entity,NotificationTypeEnum.EVALUATION_CREATION);
@@ -716,12 +725,13 @@ public class ApplicationEvaluationDao {
List<ApplicationAmendmentRequestEntity> applicationAmendmentRequestEntities =
applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(entity.getId());
if(req.getEvaluationDocument()!=null) {
log.info("Updating evaluation document for assignedApplicationId={}", assignedApplicationId);
updateApplicationEvaluation(assignedApplicationId, req.getEvaluationDocument());
}
// Fetch amendment details from the request
if(req.getAmendmentDetails()!=null) {
log.debug("Processing amendment details for evaluationId={}", entity.getId());
List<AmendmentDetailsRequest> amendmentDetailsRequests = req.getAmendmentDetails();
updateAmendmentDocumentsAndFormFields(applicationAmendmentRequestEntities, amendmentDetailsRequests);
}
@@ -734,7 +744,10 @@ public class ApplicationEvaluationDao {
}
private void validateApplicationEvaluationRequest(ApplicationEvaluationRequest req, ApplicationEntity application) {
log.debug("Validating evaluation request for applicationId={}, evaluationVersion={}",
application.getId(), application.getEvaluationVersion());
if(EvaluationVersionEnum.V2.getValue().equals(application.getEvaluationVersion())) {
log.info("Evaluation version is V2 for applicationId={}; setting checklist and criteria to null", application.getId());
req.setChecklist(null);
req.setCriteria(null);
}
@@ -1059,15 +1072,18 @@ public class ApplicationEvaluationDao {
}
public ApplicationEvaluationEntity validateApplicationEvaluation(Long id) {
log.debug("Validating existence of ApplicationEvaluationEntity with ID: {}", id);
Optional<ApplicationEvaluationEntity> entityOptional = applicationEvaluationRepository.findByIdAndIsDeletedFalse(id);
if (entityOptional.isEmpty()) {
log.warn("ApplicationEvaluationEntity not found or marked as deleted for ID: {}", id);
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_EVALUATION_NOT_FOUND, id));
}
log.info("Successfully validated ApplicationEvaluationEntity with ID: {}", id);
return entityOptional.get();
}
public void validatePreinstructor(HttpServletRequest request,Long applicationId,Long assignedApplicationId){
log.debug("Validating preinstructor access: applicationId={}, assignedApplicationId={}", applicationId, assignedApplicationId);
if (applicationId == null && assignedApplicationId == null) {
throw new CustomValidationException(
Status.BAD_REQUEST,
@@ -1091,12 +1107,14 @@ public class ApplicationEvaluationDao {
validator.validatePreInstructor(request, assignedApplications.getUserId());
}
public ApplicationEvaluationResponse getApplicationEvaluationByApplicationId(HttpServletRequest request, UserEntity user, Long applicationID, Long assignedApplicationID) {
log.info("Entering getApplicationEvaluationByApplicationId: applicationID={}, assignedApplicationID={}", applicationID, assignedApplicationID);
Long applicationId;
Long assignedApplicationId;
validatePreinstructor(request, applicationID, assignedApplicationID);
if (applicationID == null && assignedApplicationID != null) {
assignedApplicationId = assignedApplicationID;
log.debug("applicationID is null, fetching from assignedApplicationID={}", assignedApplicationId);
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId);
@@ -1124,10 +1142,14 @@ public class ApplicationEvaluationDao {
} else {
entityOptional = applicationEvaluationRepository.findFirstByIsDeletedFalseOrderByCreatedDateDesc();
}
return entityOptional.map(this::convertToResponse)
.orElseGet(() -> {
return getEvaluationResponseByApplicationid(user, applicationId, assignedApplicationId);
});
if (entityOptional.isEmpty()) {
return null;
}
ApplicationEvaluationEntity entity = entityOptional.get();
ApplicationEvaluationResponse applicationEvaluationResponse = convertToResponse(entity);
applicationEvaluationResponse.setEmailSendResponse(entity.getEmailSendResponse());
return applicationEvaluationResponse;
}
private List<EvaluationDocumentRequest> prepareEvaluationDocumentBeanList(ApplicationEvaluationEntity entity) {
List<EvaluationDocumentRequest> docRequest = new ArrayList<>();
@@ -1140,6 +1162,7 @@ public class ApplicationEvaluationDao {
public ApplicationEvaluationResponse getEvaluationResponseByApplicationid(UserEntity user, Long applicationId, Long assignedApplicationId) {
log.debug("Entering getEvaluationResponseByApplicationid with applicationId={}, assignedApplicationId={}, userId={}", applicationId, assignedApplicationId, user.getId());
ApplicationEvaluationEntity entity = new ApplicationEvaluationEntity();
ApplicationEvaluationResponse response = new ApplicationEvaluationResponse();
CallEntity call = null;
@@ -1193,6 +1216,7 @@ public class ApplicationEvaluationDao {
ApplicationEvaluationResponse response,
List<EvaluationCriteriaEntity> evaluationCriterias) {
log.info("Setting criteria responses for applicationId: {}", applicationId);
List<CriteriaResponse> criteriaResponses = getInitialCriteriaResponses(entity, applicationId);
criteriaResponses.forEach(criteriaResponse -> {
@@ -1388,6 +1412,7 @@ public class ApplicationEvaluationDao {
private void setChecklistResponses(ApplicationEvaluationEntity entity, Long applicationId, ApplicationEvaluationResponse response,
List<CallTargetAudienceChecklistEntity> checklistEntities) {
log.info("Setting checklist responses for applicationId: {}", applicationId);
List<ChecklistResponse> checklistResponses = entity.getChecklist() != null ? Utils.convertJsonToList(entity.getChecklist(), new TypeReference<List<ChecklistResponse>>() {
}) : getChecklistResponse(applicationId);
@@ -1506,6 +1531,7 @@ public class ApplicationEvaluationDao {
}
List<CriteriaResponse> getCriteriaResponse(Long applicationId) {
log.info("Getting criteria response for applicationId: {}", applicationId);
CallEntity call = getCallEntityByApplicationId(applicationId);
List<EvaluationCriteriaEntity> evaluationCriterias = getEvaluationCriterias(call);
@@ -1515,10 +1541,12 @@ public class ApplicationEvaluationDao {
}
private CallEntity getCallEntityByApplicationId(Long applicationId) {
log.info("Fetching CallEntity for applicationId: {}", applicationId);
return callRepository.findCallEntityByApplicationId(applicationId);
}
private List<EvaluationCriteriaEntity> getEvaluationCriterias(CallEntity call) {
log.info("Fetching evaluation criterias for callId: {}", call.getId());
return evaluationCriteriaRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA.getValue());
}
@@ -1665,7 +1693,7 @@ public class ApplicationEvaluationDao {
});
}
private String getLabelFromSettings(ContentResponseBean contentResponseBean) {
public String getLabelFromSettings(ContentResponseBean contentResponseBean) {
String label = contentResponseBean.getLabel();
if (contentResponseBean.getSettings() != null) {
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
@@ -1765,6 +1793,7 @@ public class ApplicationEvaluationDao {
List<ChecklistResponse> getChecklistResponse(Long applicationId) {
log.info("Fetching checklist responses for applicationId: {}", applicationId);
CallEntity call = callRepository.findCallEntityByApplicationId(applicationId);
List<CallTargetAudienceChecklistEntity> checklistEntities = callTargetAudienceChecklistRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(call.getId(), LookUpDataEntity.LookUpDataTypeEnum.CHECKLIST.getValue());
@@ -1850,7 +1879,7 @@ public class ApplicationEvaluationDao {
}
public void deleteById(Long id) {
log.info("Starting soft delete for ApplicationEvaluation with id: {}", id);
ApplicationEvaluationEntity applicationEvaluationEntity = validateApplicationEvaluation(id);
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(applicationEvaluationEntity);
applicationEvaluationEntity.setIsDeleted(true);
@@ -1872,11 +1901,13 @@ public class ApplicationEvaluationDao {
public ApplicationEvaluationResponse updateApplicationEvaluationStatus(ApplicationEntity application, AssignedApplicationsEntity assignedApplicationsEntity,
ApplicationStatusForEvaluation newStatus) {
log.info("Starting updateApplicationEvaluationStatus for applicationId: {}, assignedApplicationId: {}, newStatus: {}",
application.getId(), assignedApplicationsEntity.getId(), newStatus);
Optional<ApplicationEvaluationEntity> existingEntityOptional = applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(
assignedApplicationsEntity.getId());
ApplicationEvaluationEntity entity;
EmailSendResponse emailSendResponse = new EmailSendResponse();
if (existingEntityOptional.isPresent()) {
ApplicationEvaluationEntity existingEntity = existingEntityOptional.get();
// UserEntity userEntity = userService.validateUser(application.getUserId());
@@ -1884,18 +1915,26 @@ public class ApplicationEvaluationDao {
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(application);
List<EmailSendResponse> responses = new ArrayList<>();
if(newStatus.equals(ApplicationStatusForEvaluation.ADMISSIBLE) && Boolean.TRUE.equals(application.getStatus().equals(ApplicationStatusTypeEnum.APPOINTMENT.getValue()))){
application.setStatus(newStatus.getValue());
log.info("Status updated to ADMISSIBLE for applicationId: " + application.getId());
emailNotificationDao.sendAdmissibilityNotificationEmailForAdmissibleApplication(application);
emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
responses = List.of(emailSendResponse);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())) {
saveEmailSendResponseToEvaluation(emailSendResponse, existingEntity);
}
}
if(newStatus.equals(ApplicationStatusForEvaluation.TECHNICAL_EVALUATION) && Boolean.TRUE.equals(application.getStatus().equals(ApplicationStatusTypeEnum.ADMISSIBLE.getValue()))){
log.info("Processing technical evaluation for applicationId: {}", application.getId());
processTechnicalEvaluation(application.getId(), application, newStatus);
}
if((newStatus.equals(ApplicationStatusForEvaluation.APPROVED) || newStatus.equals(ApplicationStatusForEvaluation.REJECTED)) && application.getStatus().equals(ApplicationStatusTypeEnum.EVALUATION.getValue())) {
application.setStatus(newStatus.getValue());
log.info("Application status updated to {} for applicationId: {}", newStatus, application.getId());
}
application = applicationRepository.save(application);
@@ -1907,6 +1946,7 @@ public class ApplicationEvaluationDao {
List<ApplicationAmendmentRequestEntity> amendmentRequest = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndStatusAndIsDeletedFalse(existingEntity.getId(),List.of(ApplicationAmendmentRequestEnum.AWAITING.getValue(),ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue()));
if(amendmentRequest !=null && Boolean.FALSE.equals(amendmentRequest.isEmpty())){
log.warn("Application cannot be approved or rejected due to pending amendment requests. applicationEvaluationId: {}", existingEntity.getId());
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_CANNOT_APPROVED_OR_REJECTED));
}
String statusType = application.getStatus();
@@ -1914,11 +1954,13 @@ public class ApplicationEvaluationDao {
existingEntity.setStatus(ApplicationEvaluationStatusTypeEnum.CLOSE.getValue());
existingEntity.setClosingDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CLOSE.getValue());
log.info("Closing ApplicationEvaluation and AssignedApplication for applicationId: {}", application.getId());
}
if (existingEntity.getStartDate() != null && existingEntity.getClosingDate() != null) {
long activeDays = ChronoUnit.DAYS.between(existingEntity.getStartDate(), existingEntity.getClosingDate());
activeDays -= existingEntity.getSuspendedDays() != null ? existingEntity.getSuspendedDays() : 0;
existingEntity.setActiveDays(activeDays);
log.debug("Calculated active days for ApplicationEvaluationEntity id {}: {}", existingEntity.getId(), activeDays);
}
entity = applicationEvaluationRepository.save(existingEntity);
assignedApplicationsRepository.save(assignedApplicationsEntity);
@@ -1934,37 +1976,63 @@ public class ApplicationEvaluationDao {
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.APPROVED.getValue())))) {
application.setDateAccepted(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application.setDateAccepted(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application = applicationRepository.save(application);
// emailNotificationDao.sendAdmissibilityNotificationEmailForApprovedApplication(application);
notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_RESULT);
}
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.REJECTED.getValue())))) {
application.setDateRejected(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
application = applicationRepository.save(application);
emailNotificationDao.sendInadmissibilityEmailForRejectedApplication(application,existingEntity);
emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
responses = List.of(emailSendResponse);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())) {
saveEmailSendResponseToEvaluation(emailSendResponse, existingEntity);
}
notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_RESULT);
}
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_RESULT);
Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("{{call_name}}", application.getCall().getName());
placeHolders.put("{{protocol_number}}", String.valueOf(application.getProtocol().getProtocolNumber()));
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_RESULT);
notificationDao.sendNotificationToInstructor(placeHolders,existingEntity,NotificationTypeEnum.EVALUATION_RESULT);
return convertToResponse(entity);
ApplicationEvaluationResponse response = convertToResponse(entity);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())) {
response.setEmailSendResponse(responses);
}
return response;
}
return null;
}
private void saveEmailSendResponseToEvaluation(EmailSendResponse newResponse, ApplicationEvaluationEntity evaluationEntity) {
List<EmailSendResponse> mergedResponses = Utils.mergeEmailSendResponses(
evaluationEntity.getEmailSendResponse(), newResponse
);
evaluationEntity.setEmailSendResponse(mergedResponses);
applicationEvaluationRepository.save(evaluationEntity);
}
public ApplicationEvaluationEntity validateApplicationEvaluationByApplicationId(Long applicationId) {
log.info("Validating ApplicationEvaluation for applicationId: {}", applicationId);
return applicationEvaluationRepository
.findByApplicationIdAndIsDeletedFalse(applicationId)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_EVALUATION_NOT_FOUND)));
.orElseThrow(() -> {
log.error("ApplicationEvaluation not found for applicationId: {}", applicationId);
return new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_EVALUATION_NOT_FOUND));
});
}
public ApplicationEvaluationResponse updateApplicationEvaluation(
Long assignedApplicationId,
List<EvaluationDocumentRequest> docRequest) {
log.info("Starting updateApplicationEvaluation for assignedApplicationId: {}", assignedApplicationId);
Optional<ApplicationEvaluationEntity> entityOptional=applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApplicationId);
ApplicationEvaluationEntity applicationEvaluationEntity =null;
ApplicationEvaluationEntity oldApplicationEvaluation = Utils.getClonedEntityForData(entityOptional.get());
@@ -1986,14 +2054,17 @@ public class ApplicationEvaluationDao {
applicationEvaluationEntity.setEvaluationDocument(updatedEvaluationDocJson);
}
ApplicationEvaluationEntity savedEntity = applicationEvaluationRepository.save(applicationEvaluationEntity);
log.info("Saved ApplicationEvaluationEntity with id: {}", savedEntity.getId());
/** 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());
log.info("Version history logged for update on ApplicationEvaluationEntity id: {}", savedEntity.getId());
return convertToResponse(savedEntity);
}
public ApplicationEvaluationFormResponse createApplicationEvaluation(HttpServletRequest request, ApplicationEvaluationFormRequestBean applicationEvaluationFormRequestBean, Long evaluationFormId, Long assignedApplicationId){
log.info("Start createApplicationEvaluation - assignedApplicationId: {}, evaluationFormId: {}", assignedApplicationId, evaluationFormId);
UserEntity user = validator.validateUser(request);
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsService.validateAssignedApplication(assignedApplicationId);
ApplicationEntity application = applicationService.validateApplication(assignedApplicationsEntity.getApplication().getId());
@@ -2006,6 +2077,7 @@ public class ApplicationEvaluationDao {
ApplicationEvaluationEntity entity = applicationEvaluationService.validateApplicationEvaluation(evaluationResponse.getId());
//Handling Application Evaluation form
EvaluationFormEntity evaluationFormEntity = evaluationFormService.validateEvaluationForm(evaluationFormId);
validateFormFields(applicationEvaluationFormRequestBean,evaluationFormEntity);
@@ -2014,7 +2086,9 @@ public class ApplicationEvaluationDao {
validateFormFieldCustom(applicationEvaluationFormRequestBean.getFormFields(),entity,evaluationFormEntity);
ApplicationEvaluationFormEntity applicationEvaluationFormEntity = getApplicationEvaluationFormOrCreate(evaluationFormEntity,entity);
createOrUpdateMultipleFormFields(applicationEvaluationFormRequestBean.getFormFields(), applicationEvaluationFormEntity, evaluationFormEntity);
return processEvaluationForm(entity);
ApplicationEvaluationFormResponse response = processEvaluationForm(entity);
response.setEmailSendResponse(evaluationResponse.getEmailSendResponse());
return response;
}
private ApplicationEvaluationFormEntity getApplicationEvaluationFormOrCreate(EvaluationFormEntity evaluationFormEntity, ApplicationEvaluationEntity applicationEvaluationEntity) {
@@ -2054,6 +2128,7 @@ public class ApplicationEvaluationDao {
String fieldId = requestField.getFieldId();
if (!contentMap.containsKey(fieldId)) {
log.warn("Field ID not found in evaluation form: {}", fieldId);
validator.addError(MessageFormat.format(Translator.toLocale(GepafinConstant.FIELD_ID_NOT_FOUND), fieldId));
}
@@ -2081,6 +2156,7 @@ public class ApplicationEvaluationDao {
ApplicationEvaluationFormEntity applicationEvaluationFormEntity,
List<ApplicationEvaluationFormFieldEntity> applicationEvaluationFormFieldEntities,
EvaluationFormEntity evaluationFormEntity,FieldValidator fieldValidator){
log.debug("Starting createOrUpdateApplicationEvaluationFormField for fieldId: {}", applicationFormFieldRequestBean.getFieldId());
ApplicationEvaluationFormFieldEntity applicationEvaluationFormFieldEntity = new ApplicationEvaluationFormFieldEntity();
validateFileUploadDocuments(applicationFormFieldRequestBean, evaluationFormEntity);
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
@@ -2121,6 +2197,7 @@ public class ApplicationEvaluationDao {
}
private List<Long> validateFileUploadDocuments(ApplicationFormFieldRequestBean applicationFormFieldRequestBean, EvaluationFormEntity evaluationFormEntity) {
log.debug("Validating file upload documents for fieldId: {}", applicationFormFieldRequestBean.getFieldId());
List<Long> documentIds=null;
List<ContentResponseBean> contentResponseBeans=evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(evaluationFormEntity).getContent();
@@ -2145,6 +2222,9 @@ public class ApplicationEvaluationDao {
private List<ApplicationEvaluationFormFieldReponseBean> createEvaluationFormFieldResponse(
List<ApplicationEvaluationFormFieldEntity> evaluationFormFieldEntities,
ApplicationEvaluationFormEntity applicationEvaluationFormEntity){
log.info("Starting to create evaluation form field response for EvaluationFormEntity ID: {}",
applicationEvaluationFormEntity.getEvaluationForm().getId());
List<ApplicationEvaluationFormFieldReponseBean> evaluationFormFieldResponseBeans = new ArrayList<>();
List<ContentResponseBean> contentResponseBeans =evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(applicationEvaluationFormEntity.getEvaluationForm()).getContent();
@@ -2236,6 +2316,7 @@ public class ApplicationEvaluationDao {
public ApplicationEvaluationFormResponse getApplicationEvaluationForm(HttpServletRequest request, Long applicationId, Long assignedApplicationId ){
log.debug("Fetching evaluation form. applicationId: {}, assignedApplicationId: {}", applicationId, assignedApplicationId);
if (applicationId == null && assignedApplicationId == null) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.EITHER_APPLICATION_ID_OR_ASSIGNED_APPLICATION_ID_MUST_BE_PROVIDED));
}
@@ -2259,6 +2340,7 @@ public class ApplicationEvaluationDao {
}
response.setCompanyVatNumber(company.getVatNumber());
response.setCompanyCodiceAteco(company.getCodiceAteco());
response.setEmailSendResponse(evaluationEntity.getEmailSendResponse());
return response;
}
@@ -2464,24 +2546,26 @@ public class ApplicationEvaluationDao {
return false;
}
private void processTechnicalEvaluation(Long applicationId, ApplicationEntity applicationEntity, ApplicationStatusForEvaluation status){
log.info("Starting technical evaluation processing for applicationId: {}", applicationId);
Optional<ApplicationEvaluationEntity> evaluationEntityOpt = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
if (evaluationEntityOpt.isPresent()){
ApplicationEvaluationEntity evaluationEntity = evaluationEntityOpt.get();
String criteriaJson = evaluationEntity.getCriteria();
if (criteriaJson != null){
Integer totalScore = calculateTotalScore(evaluationEntity.getCriteria());
if (totalScore > 40) {
BigDecimal totalScore = calculateTotalScore(evaluationEntity.getCriteria());
if (totalScore.compareTo(new BigDecimal("40")) > 0) {
applicationEntity.setStatus(status.getValue());
log.info("Status updated to TECHNICAL_EVALUATION for applicationId: " + applicationId);
log.info("Status updated to TECHNICAL_EVALUATION for applicationId: {}", applicationId);
}
else{
log.warn("Insufficient score ({}) for applicationId: {}. Throwing validation exception.", totalScore, applicationId);
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.INSUFFICIENT_SCORE_MESSAGE));
}
}
}
}
private Integer calculateTotalScore(String criteriaJson){
private BigDecimal calculateTotalScore(String criteriaJson){
try {
ObjectMapper objectMapper = new ObjectMapper();
// Convert JSON string to List of Maps
@@ -2489,15 +2573,19 @@ public class ApplicationEvaluationDao {
});
// Sum all scores (ignoring null scores)
Integer totalScore = criteriaList.stream()
.mapToInt(obj -> obj.get("score") != null ? ((Number) obj.get("score")).intValue() : 0)
.sum();
BigDecimal totalScore = criteriaList.stream()
.map(obj -> {
Object score = obj.get("score");
return score != null ? new BigDecimal(score.toString()) : BigDecimal.ZERO;
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("Total score calculated successfully: {}", totalScore);
return totalScore;
}
catch (Exception e) {
log.error(" Error parsing criteria JSON: {}", e.getMessage());
return 0;
return BigDecimal.ZERO;
}
}

View File

@@ -1,7 +1,6 @@
package net.gepafin.tendermanagement.dao;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -13,12 +12,14 @@ 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.ApplicationAmendmentRequestEntity;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.ApplicationEvaluationEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
import net.gepafin.tendermanagement.model.request.AppointmentCreationRequest;
@@ -37,6 +38,7 @@ 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.AmazonS3Service;
import net.gepafin.tendermanagement.service.ApplicationService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.feignClient.AppointmentApiService;
@@ -60,12 +62,7 @@ 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.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -141,6 +138,18 @@ public class AppointmentDao {
@Autowired
private ApplicationEvaluationServiceImpl applicationEvaluationService;
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private ApplicationDao applicationDao;
@Autowired
private ApplicationAmendmentRequestDao applicationAmendmentRequestDao;
@Autowired
private ApplicationEvaluationDao applicationEvaluationDao;
private final Map<Long, ExecutorService> executorMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, ExecutorService> threadForDocumentMap = new ConcurrentHashMap<>();
@@ -148,10 +157,11 @@ public class AppointmentDao {
private static final ThreadLocal<Long> threadLocalHubId = new ThreadLocal<>();
public NdgResponse checkNdgForAppointment(Long applicationId) {
log.info("Starting NDG check for appointment. applicationId: {}", applicationId);
ApplicationEntity application = applicationService.validateApplication(applicationId);
NdgResponse ndgResponse = new NdgResponse();
if (application.getNdgStatus() != null && application.getNdgStatus().equalsIgnoreCase(GepafinConstant.NDG_IN_PROGRESS)) {
log.warn("NDG generation already in progress. applicationId: {}", applicationId);
throw new CustomValidationException(Status.SUCCESS, Translator.toLocale(GepafinConstant.NDG_GENERATION_IS_IN_PROGRESS));
}
@@ -161,6 +171,7 @@ public class AppointmentDao {
}
// Update application status
log.info("Updating NDG status to IN_PROGRESS. applicationId: {}", applicationId);
application.setNdgStatus(GepafinConstant.NDG_IN_PROGRESS);
applicationRepository.save(application);
@@ -168,12 +179,186 @@ public class AppointmentDao {
HubEntity hub = hubRepository.findByHubId(application.getHubId());
loginToOdessa(hub, application);
startAsyncNdgProcessing(applicationId);
log.info("NDG check initiation completed. applicationId: {}", applicationId);
return ndgResponse;
}
private HubEntity loginToOdessa(HubEntity hub, ApplicationEntity application) {
// private HubEntity loginToOdessa(HubEntity hub, ApplicationEntity application) {
//
// int maxRetries = 3;
// int attempt = 0;
// boolean success = false;
// while (attempt < maxRetries && !success) {
// attempt++;
// 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);
// Map<String, Object> body = Collections.emptyMap();
// ResponseEntity<Object> responseLogin = appointmentApiService.loginWithOdessa(authJwtToken, source, context, user, password, body);
// 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);
// log.info("Saved new authToken and areaCode for Hub.");
// success = true;
// return hub;
// } else {
// throw new RuntimeException("Login response is missing a valid tokenId for login to odessa system, please try again.");
// }
// }
// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.ERROR_IN_GENERATING_NDG_TRY_AGAIN));
// } catch (FeignException.Forbidden forbiddenException) {
// log.error("Failed to login to odessa due to some error");
//
// // Extract raw response body
// String responseBody = forbiddenException.contentUTF8(); // Extract raw JSON response
//
// // Parse JSON to check for "PasswordExpired"
// try {
// ObjectMapper objectMapper = new ObjectMapper();
// JsonNode rootNode = objectMapper.readTree(responseBody);
// JsonNode errorsNode = rootNode.path("errors");
//
// if (errorsNode.isArray()) {
// for (JsonNode error : errorsNode) {
// // Check the main errorCode
// if (GepafinConstant.PASSWORD_EXPIRED.equals(error.path("errorCode").asText())) {
// application.setNdgStatus(GepafinConstant.NDG_FAILED);
// applicationRepository.save(application);
// throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
// }
//
// // Check inside "subErrors"
// JsonNode subErrorsNode = error.path("subErrors");
// if (subErrorsNode.isArray()) {
// for (JsonNode subError : subErrorsNode) {
// if (GepafinConstant.PASSWORD_EXPIRED.equals(subError.path("errorCode").asText())) {
// application.setNdgStatus(GepafinConstant.NDG_FAILED);
// applicationRepository.save(application);
// throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
// }
// }
// }
// }
// }
// } catch (IOException e) {
// log.error("Error parsing JSON response: {}", e.getMessage());
// }
// } catch (Exception e) {
// log.error("Failed to authenticate user on Odessa : {}", e.getMessage(), e);
// throw new RuntimeException("Authentication failed on Odessa. try again", e);
// }
// }
// return null;
// }
//
//
// private HubEntity authenticateAndSaveToken(HubEntity hub) {
//
// int maxRetries = 3;
// int attempt = 0;
// boolean success = false;
// while (attempt < maxRetries && !success) {
// attempt++;
// 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);
// // 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);
//
// log.info("Saved new authToken and areaCode for Hub.");
// success = true;
// 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 (FeignException.Forbidden forbiddenException) {
// log.error("Failed to login to odessa due to some error occurred.");
//
// // Extract raw response body
// String responseBody = forbiddenException.contentUTF8(); // Extract raw JSON response
//
// // Parse JSON to check for "PasswordExpired"
// try {
// ObjectMapper objectMapper = new ObjectMapper();
// JsonNode rootNode = objectMapper.readTree(responseBody);
// JsonNode errorsNode = rootNode.path("errors");
//
// if (errorsNode.isArray()) {
// for (JsonNode error : errorsNode) {
// // Check the main errorCode
// if (GepafinConstant.PASSWORD_EXPIRED.equals(error.path("errorCode").asText())) {
// throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
// }
//
// // Check inside "subErrors"
// JsonNode subErrorsNode = error.path("subErrors");
// if (subErrorsNode.isArray()) {
// for (JsonNode subError : subErrorsNode) {
// if (GepafinConstant.PASSWORD_EXPIRED.equals(subError.path("errorCode").asText())) {
// throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
// }
// }
// }
// }
// }
// } catch (IOException e) {
// log.error("Error parsing JSON response: {}", e.getMessage());
// }
// } catch (Exception e) {
// log.error("Failed to authenticate user on Odessa : {}", e.getMessage(), e);
// throw new RuntimeException("Authentication failed on Odessa. try again", e);
// }
// }
// return null;
// }
private void loginToOdessa(HubEntity hub, ApplicationEntity application) {
log.info("Starting login to Odessa. HubId: {}, ApplicationId: {}", hub.getId(), application.getId());
performOdessaLogin(hub, application);
}
private HubEntity authenticateAndSaveToken(HubEntity hub, ApplicationEntity application) {
return performOdessaLogin(hub, application);
}
private HubEntity performOdessaLogin(HubEntity hub, ApplicationEntity application) {
int maxRetries = 3;
int attempt = 0;
while (attempt < maxRetries) {
attempt++;
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);
@@ -181,11 +366,10 @@ public class AppointmentDao {
Map<String, Object> body = Collections.emptyMap();
ResponseEntity<Object> responseLogin = appointmentApiService.loginWithOdessa(authJwtToken, source, context, user, password, body);
if (responseLogin.getStatusCode() == HttpStatus.OK) {
log.info("Login successful to odessa. Parsing response.");
log.info("Login to Odessa successful. Parsing response. HubId: {}", hub.getId());
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());
@@ -193,57 +377,58 @@ public class AppointmentDao {
log.info("Saved new authToken and areaCode for Hub.");
return hub;
} else {
log.error("Login response from Odessa missing tokenId. HubId: {}", hub.getId());
throw new RuntimeException("Login response is missing a valid tokenId for login to odessa system, please try again.");
}
}
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.ERROR_IN_GENERATING_NDG_TRY_AGAIN));
} catch (FeignException.Forbidden forbiddenException) {
log.error("Failed to login to odessa due to forbidden error.");
CheckPasswordExpiredOrErrorInResponse(application, forbiddenException);
} catch (Exception e) {
log.error("Failed to authenticate user on Odessa (Attempt {}): {}", attempt, e.getMessage(), e);
}
catch (FeignException.Forbidden forbiddenException) {
logForbiddenError();
}
throw new RuntimeException("Max retries exceeded. Failed to login to Odessa.");
}
private void CheckPasswordExpiredOrErrorInResponse(ApplicationEntity application, FeignException.Forbidden forbiddenException) {
// Extract raw response body
String responseBody = forbiddenException.contentUTF8(); // Extract raw JSON response
String responseBody = forbiddenException.contentUTF8();
// Parse JSON to check for "PasswordExpired"
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(responseBody);
JsonNode errorsNode = rootNode.path("errors");
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(responseBody);
JsonNode errorsNode = rootNode.path("errors");
if (errorsNode.isArray()) {
for (JsonNode error : errorsNode) {
// Check the main errorCode
if (GepafinConstant.PASSWORD_EXPIRED.equals(error.path("errorCode").asText())) {
application.setNdgStatus(GepafinConstant.NDG_FAILED);
applicationRepository.save(application);
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
}
if (errorsNode.isArray()) {
for (JsonNode error : errorsNode) {
if (GepafinConstant.PASSWORD_EXPIRED.equals(error.path("errorCode").asText())) {
if (application != null) {
application.setNdgStatus(GepafinConstant.NDG_FAILED);
applicationRepository.save(application);
}
log.warn("Detected PASSWORD_EXPIRED error during Odessa login. ApplicationId: {}", application.getId());
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
}
// Check inside "subErrors"
JsonNode subErrorsNode = error.path("subErrors");
if (subErrorsNode.isArray()) {
for (JsonNode subError : subErrorsNode) {
if (GepafinConstant.PASSWORD_EXPIRED.equals(subError.path("errorCode").asText())) {
application.setNdgStatus(GepafinConstant.NDG_FAILED);
applicationRepository.save(application);
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
}
JsonNode subErrorsNode = error.path("subErrors");
if (subErrorsNode.isArray()) {
for (JsonNode subError : subErrorsNode) {
if (GepafinConstant.PASSWORD_EXPIRED.equals(subError.path("errorCode").asText())) {
if (application != null) {
application.setNdgStatus(GepafinConstant.NDG_FAILED);
applicationRepository.save(application);
}
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
}
}
}
} catch (IOException e) {
log.error("Error parsing JSON response: {}", e.getMessage());
}
// Regenerate the token and retry
loginToOdessa(hub, application);
}
catch (Exception e) {
log.error("Failed to authenticate user on Odessa : {}", e.getMessage(), e);
throw new RuntimeException("Authentication failed on Odessa. try again", e);
}
return null;
} catch (IOException e) {
log.error("Unexpected exception during Odessa login.Error: {}",e.getMessage(), e);
}
}
private void startAsyncNdgProcessing(Long applicationId) {
@@ -280,6 +465,7 @@ public class AppointmentDao {
private void processNdgGeneration(Long applicationId) {
// Validate application, company, and hub
log.info("Starting NDG generation process for applicationId: {}", applicationId);
ApplicationEntity application = applicationService.validateApplication(applicationId);
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
HubEntity hub = hubRepository.findByHubId(application.getHubId());
@@ -292,7 +478,7 @@ public class AppointmentDao {
try {
// Authenticate and fetch token if required
if (hub.getAppointmentAuthTokenId() == null || hub.getAreaCode() == null) {
authenticateAndSaveToken(hub);
authenticateAndSaveToken(hub, application);
}
String authorizationToken = getBearerToken(hub);
@@ -307,14 +493,15 @@ public class AppointmentDao {
handleNdgPolling(application, company, hub, authorizationToken);
}
} catch (Exception e) {
log.error("Error during NDG generation for applicationId: {}", applicationId, e);
log.error("Exception occurred during NDG generation. ApplicationId: {}, CompanyId: {}, HubId: {}, Error: {}",
applicationId, company.getId(), hub.getId(), e.getMessage(), e);
}
}
private void handleNdgPolling(ApplicationEntity application, CompanyEntity company, HubEntity hub, String authorizationToken) {
try {
log.info("Starting NDG polling for applicationId: {}", application.getId());
log.info("Starting NDG polling for applicationId: {}, CompanyId: {}, HubId: {}", application.getId(),company.getId(), hub.getId());
long startTime = System.currentTimeMillis();
while (true) {
@@ -326,12 +513,13 @@ public class AppointmentDao {
try {
// Fetch Visura list and attempt to parse NDG
String visuraListJson = getVisuraList(application.getIdVisura(), authorizationToken, application, hub);
log.debug("Parsing NDG from visura list response | ApplicationId: {}", application.getId());
String ndg = parseNdgFromVisuraListResponse(visuraListJson);
if (isNdgValid(ndg)) {
// CompanyEntity oldCompanyData = Utils.getClonedEntityForData(company);
// ApplicationEntity oldApplicationData = Utils.getClonedEntityForData(application);
log.info("Valid NDG retrieved: {} | ApplicationId: {}", ndg, application.getId());
company.setNdg(ndg);
application.setNdg(ndg);
application.setNdgStatus(GepafinConstant.NDG_GENERATED);
@@ -339,9 +527,13 @@ public class AppointmentDao {
applicationRepository.save(application);
companyRepository.save(company);
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluation(application.getApplicationEvaluationId());
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.NDG_GENERATION);
// Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.NDG_GENERATION);
Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("{{call_name}}", application.getCall().getName());
placeHolders.put("{{protocol_number}}", String.valueOf(application.getProtocol().getProtocolNumber()));
notificationDao.sendNotificationToInstructor(placeHolders, applicationEvaluationEntity, NotificationTypeEnum.NDG_GENERATION);
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.NDG_GENERATION);
notificationDao.sendNotificationToSuperUser(application, placeHolders, NotificationTypeEnum.NDG_GENERATION);
log.info("NDG saved successfully for applicationId: {}", application.getId());
break;
}
@@ -389,14 +581,18 @@ public class AppointmentDao {
companyRepository.save(company);
applicationRepository.save(application);
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluation(application.getApplicationEvaluationId());
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.NDG_GENERATION);
// Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.NDG_GENERATION);
Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("{{call_name}}", application.getCall().getName());
placeHolders.put("{{protocol_number}}", String.valueOf(application.getProtocol().getProtocolNumber()));
notificationDao.sendNotificationToInstructor(placeHolders, applicationEvaluationEntity, NotificationTypeEnum.NDG_GENERATION);
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.NDG_GENERATION);
notificationDao.sendNotificationToSuperUser(application, placeHolders, NotificationTypeEnum.NDG_GENERATION);
log.info("NDG saved for applicationId: {}, {}", application.getId(), application.getNdg());
}
private String getVisuraList(String idVisura, String authorizationToken, ApplicationEntity application, HubEntity hub) {
log.info("Initiating Visura list retrieval | ApplicationId: {}, HubId: {}, IdVisura: {}", application.getId(), hub.getId(), idVisura);
AppointmentVisuraListRequest visuraListRequest = new AppointmentVisuraListRequest();
AppointmentVisuraListRequest.VisuraFilter filter = new AppointmentVisuraListRequest.VisuraFilter();
filter.setIdVisura(idVisura);
@@ -407,95 +603,20 @@ public class AppointmentDao {
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...");
log.warn("403 Forbidden while fetching Visura list. Attempting token regeneration | ApplicationId: {}, HubId: {}", application.getId(), hub.getId());
// Regenerate the token and retry
String newAuthorizationToken = regenerateTokenAndSave(hub);
String newAuthorizationToken = regenerateTokenAndSave(hub, application);
return getVisuraList(idVisura, newAuthorizationToken, application, hub);
} catch (Exception e) {
log.error("Failed to fetch Ndg code: {}", e.getMessage(), e);
log.error("Error while fetching Visura list | ApplicationId: {}, HubId: {}, Error: {}", application.getId(), hub.getId(), e.getMessage(), e);
throw new RuntimeException("Error fetching Ndg List", e);
}
}
private HubEntity authenticateAndSaveToken(HubEntity 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);
// 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);
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 (FeignException.Forbidden forbiddenException) {
logForbiddenError();
// Extract raw response body
String responseBody = forbiddenException.contentUTF8(); // Extract raw JSON response
// Parse JSON to check for "PasswordExpired"
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(responseBody);
JsonNode errorsNode = rootNode.path("errors");
if (errorsNode.isArray()) {
for (JsonNode error : errorsNode) {
// Check the main errorCode
if (GepafinConstant.PASSWORD_EXPIRED.equals(error.path("errorCode").asText())) {
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
}
// Check inside "subErrors"
JsonNode subErrorsNode = error.path("subErrors");
if (subErrorsNode.isArray()) {
for (JsonNode subError : subErrorsNode) {
if (GepafinConstant.PASSWORD_EXPIRED.equals(subError.path("errorCode").asText())) {
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
}
}
}
}
}
} catch (IOException e) {
log.error("Error parsing JSON response: {}", e.getMessage());
}
// Regenerate the token and retry
regenerateTokenAndSave(hub);
} catch (Exception e) {
log.error("Failed to authenticate user on Odessa : {}", e.getMessage(), e);
throw new RuntimeException("Authentication failed on Odessa. try again", e);
}
return null;
}
private AppointmentLoginResponse retrieveNdgByVatNumber(String vatNumber, String authorizationToken, HubEntity hub, ApplicationEntity application) {
try {
log.info("Initiating NDG retrieval by VAT number | ApplicationId: {}, HubId: {}, VAT: {}", application.getId(), hub.getId(), vatNumber);
// Prepare the NDG request
AppointmentNdgRequest ndgRequest = getAppointmentNdgRequest(vatNumber);
// Call the API to retrieve NDG
@@ -504,19 +625,21 @@ public class AppointmentDao {
// Parse and return the NDG response
return parseNdgResponse(responseJson);
} catch (FeignException.Forbidden forbiddenException) {
log.error("403 Forbidden during NDG retrieval | ApplicationId: {}, HubId: {}", application.getId(), hub.getId());
logForbiddenError();
// Regenerate the token and retry
String newAuthorizationToken = regenerateTokenAndSave(hub);
String newAuthorizationToken = regenerateTokenAndSave(hub, application);
return retrieveNdgByVatNumber(vatNumber, newAuthorizationToken, hub, application);
} catch (Exception e) {
log.error("Failed to retrieve NDG by VAT number: {}", e.getMessage(), e);
log.error("Error during NDG retrieval | ApplicationId: {}, HubId: {}, Message: {}", application.getId(), hub.getId(), e.getMessage(), e);
throw new RuntimeException("NDG retrieval failed.", e);
}
}
private String regenerateTokenAndSave(HubEntity hub) {
hub = authenticateAndSaveToken(hub);
return "Bearer " + hub.getAppointmentAuthTokenId();
private String regenerateTokenAndSave(HubEntity hub, ApplicationEntity application) {
hub = authenticateAndSaveToken(hub, application);
return "Bearer " + hub.getAppointmentAuthTokenId();
}
private AppointmentLoginResponse createVisura(CompanyEntity company, String authorizationToken, HubEntity hub) {
@@ -529,7 +652,7 @@ public class AppointmentDao {
} catch (FeignException.Forbidden forbiddenException) {
logForbiddenError();
// Regenerate the token and retry
String newAuthorizationToken = regenerateTokenAndSave(hub);
String newAuthorizationToken = regenerateTokenAndSave(hub, null);
return createVisura(company, newAuthorizationToken, hub);
} catch (Exception e) {
log.error("Failed to create Visura for Ndg : {}", e.getMessage());
@@ -544,6 +667,7 @@ public class AppointmentDao {
private static AppointmentNdgRequest getAppointmentNdgRequest(String vatNumber) {
log.info("Creating Appointment NDG Request | VAT Number: {}", vatNumber);
AppointmentNdgRequest request = new AppointmentNdgRequest();
AppointmentNdgRequest.Filter filter = new AppointmentNdgRequest.Filter();
filter.setPartitaIva(vatNumber);
@@ -674,6 +798,7 @@ public class AppointmentDao {
public AppointmentCreationResponse createAppointment(Long applicationId, CreateAppointmentRequest createAppointmentRequest) {
// Validate the application
log.info("Starting appointment creation for applicationId: {}", applicationId);
ApplicationEntity application = applicationService.validateApplication(applicationId);
AppointmentCreationResponse appointmentCreationResponse = new AppointmentCreationResponse();
@@ -696,14 +821,15 @@ public class AppointmentDao {
}
if (application.getNdg() == null && Objects.equals(application.getNdgStatus(), GepafinConstant.NDG_IN_PROGRESS)) {
log.warn("NDG in progress but not available for applicationId: {}", applicationId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.NDG_NOT_FOUND_FOR_APPLICATION));
}
hub = authenticateAndSaveToken(hub);
// Generate authorization token and fetch template data
String authorizationToken = getBearerToken(hub);
String authorizationToken = regenerateTokenAndSave(hub, application);
Long appointmentTemplateId = application.getCall().getAppointmentTemplateId();
if (appointmentTemplateId == null) {
log.error("Missing appointment template ID for applicationId: {}", applicationId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPOINTMENT_CANNOT_BE_CREATED));
}
ResponseEntity<Object> response = appointmentApiService.getAppointmentTemplateForTemplateCreation(authorizationToken, appointmentTemplateId);
@@ -720,13 +846,16 @@ public class AppointmentDao {
// Build the appointment request body
AppointmentCreationRequest appointmentCreationRequest = buildAppointmentCreationRequest(applicationId, createAppointmentRequest, appointmentTemplateId,
templateRichiestaData);
log.info("AppointmentCreationRequest : {}", appointmentCreationRequest);
String appointmentRequestBody = Utils.convertObjectToJson(appointmentCreationRequest);
// Make API call to create the appointment
log.info("Context:{}, Authorization Token : {}, RequestBody : {}", context, authorizationToken, appointmentRequestBody);
ResponseEntity<Object> appointmentResponse = appointmentApiService.createAppointment(authorizationToken, context, appointmentRequestBody);
String appointmentId = extractAppointmentIdFromResponse(appointmentResponse);
if (appointmentId == null) {
log.error("Failed to extract appointment ID from response for applicationId: {}", applicationId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPOINTMENT_NOT_CREATED));
}
// Update application with the appointment ID
@@ -742,8 +871,8 @@ public class AppointmentDao {
return appointmentCreationResponse;
} catch (FeignException.Forbidden forbiddenException) {
log.error("403 Forbidden received while retrieving template. Regenerating token...");
regenerateTokenAndSave(hub);
log.error("403 Forbidden received while retrieving template. Attempting to regenerate token and retry. Application ID: {}", applicationId);
regenerateTokenAndSave(hub, application);
return createAppointment(applicationId, createAppointmentRequest);
}
}
@@ -751,12 +880,32 @@ public class AppointmentDao {
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();
log.info("Appointment API Response : {}", appointmentResponse.getBody());
try {
Map<String, Object> responseBody = (Map<String, Object>) appointmentResponse.getBody();
// 1. Try to get appointment ID from data.id
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();
}
}
// 2. If ID not present, check errors[0].cause.errorDescription
if (responseBody.containsKey(GepafinConstant.ERROR_STRING)) {
List<Map<String, Object>> errors = (List<Map<String, Object>>) responseBody.get(GepafinConstant.ERROR_STRING);
if (errors != null && !errors.isEmpty()) {
Map<String, Object> firstError = errors.get(0);
if (firstError.containsKey(GepafinConstant.CAUSE_STRING)) {
Map<String, Object> cause = (Map<String, Object>) firstError.get(GepafinConstant.CAUSE_STRING);
if (cause != null && cause.containsKey(GepafinConstant.ERROR_DESCRIPTION_STRING)) {
String errorDescription = cause.get(GepafinConstant.ERROR_DESCRIPTION_STRING).toString();
log.warn("Appointment creation failed: {}", errorDescription);
}
}
}
}
} catch (Exception e) {
log.error("Error while extracting appointment ID or parsing error message", e);
}
}
return null;
@@ -786,20 +935,20 @@ public class AppointmentDao {
JsonNode prodottoNode = richiestaNode.path(AppointmentApiConstant.PRODOTTO);
String prodottoCode = prodottoNode.path(AppointmentApiConstant.PRODOTTO_CODE).asText();
richiestaCliente.setCodProdotto(prodottoCode);
richiestaCliente.setIdMotivazione(getIntValue(richiestaNode));
richiestaCliente.setCodAbi(getTextValue(richiestaNode, AppointmentApiConstant.COD_ABI));
richiestaCliente.setCodCab(getTextValue(richiestaNode, AppointmentApiConstant.COD_CAB));
richiestaCliente.setIdNota(getTextValue(richiestaNode, AppointmentApiConstant.ID_NOTA));
richiestaCliente.setImportoAgevolato(getTextValue(richiestaNode, AppointmentApiConstant.IMPORTO_AGEVOLATO));
richiestaCliente.setImportoMedioLungoTermine(getTextValue(richiestaNode, AppointmentApiConstant.IMPORTO_MEDIOLUNGO_TERMINE));
richiestaCliente.setCodTipoProdotto(getTextValue(richiestaNode, AppointmentApiConstant.COD_TIPO_PRODOTTO));
richiestaCliente.setCodCategoriaProdotto(getTextValue(richiestaNode, AppointmentApiConstant.COD_CATEGORIA_PRODOTTO));
richiestaCliente.setCodFormaTecnica(getTextValue(richiestaNode, AppointmentApiConstant.COD_FORMATECNICA));
richiestaCliente.setCodOperazione(getTextValue(richiestaNode, AppointmentApiConstant.COD_OPERAZIONE));
richiestaCliente.setCodProdotto(prodottoCode);
richiestaCliente.setIdMotivazione(getIntValue(richiestaNode));
richiestaCliente.setCodAbi(getTextValue(richiestaNode, AppointmentApiConstant.COD_ABI));
richiestaCliente.setCodCab(getTextValue(richiestaNode, AppointmentApiConstant.COD_CAB));
richiestaCliente.setIdNota(getTextValue(richiestaNode, AppointmentApiConstant.ID_NOTA));
richiestaCliente.setImportoAgevolato(getTextValue(richiestaNode, AppointmentApiConstant.IMPORTO_AGEVOLATO));
richiestaCliente.setImportoMedioLungoTermine(getTextValue(richiestaNode, AppointmentApiConstant.IMPORTO_MEDIOLUNGO_TERMINE));
richiestaCliente.setCodTipoProdotto(getTextValue(richiestaNode, AppointmentApiConstant.COD_TIPO_PRODOTTO));
richiestaCliente.setCodCategoriaProdotto(getTextValue(richiestaNode, AppointmentApiConstant.COD_CATEGORIA_PRODOTTO));
richiestaCliente.setCodFormaTecnica(getTextValue(richiestaNode, AppointmentApiConstant.COD_FORMATECNICA));
richiestaCliente.setCodOperazione(getTextValue(richiestaNode, AppointmentApiConstant.COD_OPERAZIONE));
richiestaClienteList.add(richiestaCliente);
}
richiestaClienteList.add(richiestaCliente);
}
input.setRichiestaCliente(richiestaClienteList);
appointmentCreationRequest.setInput(input);
@@ -857,16 +1006,44 @@ public class AppointmentDao {
}
public DocumentUploadResponse uploadDocumentToExternalSystem(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
log.info("Initiating upload to external system for documentId: {}", documentId);
// Check if the document is already being processed
DocumentEntity systemDoc = documentDao.validateDocument(documentId);
ApplicationEntity application = null;
if (systemDoc != null) {
DocumentSourceTypeEnum sourceType = DocumentSourceTypeEnum.valueOf(systemDoc.getSource());
switch (sourceType) {
case APPLICATION:
application = applicationDao.validateApplication(systemDoc.getSourceId());
break;
case AMENDMENT:
ApplicationAmendmentRequestEntity applicationAmendmentEntity = applicationAmendmentRequestDao.validateApplicationAmendmentRequest(systemDoc.getSourceId());
application = applicationDao.validateApplication(applicationAmendmentEntity.getApplicationId());
break;
case EVALUATION:
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationDao.validateApplicationEvaluation(systemDoc.getSourceId());
application = applicationDao.validateApplication(applicationEvaluationEntity.getApplicationId());
break;
case CALL:
break;
default:
log.warn("Unhandled document source type: {}", sourceType);
break;
}
}
Claims claims = tokenProvider.getClaimsFromToken(tokenProvider.extractTokenFromRequest(request));
Long hubId = Utils.extractHubIdFromPayload(claims.getSubject());
// Authenticate the hub before proceeding
HubEntity hub = hubRepository.findByHubId(hubId);
authenticateAndSaveToken(hub);
if (systemDoc.getDocumentAttachmentId() != null) {
authenticateAndSaveToken(hub, application);
if (systemDoc != null && 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();
@@ -886,11 +1063,12 @@ public class AppointmentDao {
});
threadForDocumentMap.put(documentId, executor);
ApplicationEntity finalApplication = application;
executor.submit(() -> {
threadLocalHubId.set(hubId);
try {
log.info("Starting async document upload for documentId: {}", documentId);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest, finalApplication);
} catch (Exception e) {
log.error("Error in async document upload for documentId: {}", documentId, e);
} finally {
@@ -906,7 +1084,8 @@ public class AppointmentDao {
return null;
}
private void uploadDocumentToExternalSystemSync(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
private void uploadDocumentToExternalSystemSync(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest, ApplicationEntity application) {
log.info("Starting sync document upload for documentId: {}", documentId);
// Synchronous upload logic
DocumentEntity systemDoc = documentDao.validateDocument(documentId);
@@ -937,6 +1116,7 @@ public class AppointmentDao {
DocumentUploadResponse parsedResponse = parseDocumentUploadResponse(responseData);
if (parsedResponse == null) {
log.error("Upload failed: parsed response is null for documentId: {}", documentId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.ERROR_UPLOADING_DOCUMENT));
}
@@ -946,9 +1126,9 @@ public class AppointmentDao {
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);
log.error("403 Forbidden from external system during upload for documentId: {}. Retrying with new token...", documentId);
regenerateTokenAndSave(hub, application);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest, application);
} 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));
@@ -979,12 +1159,12 @@ public class AppointmentDao {
private File downloadFileFromS3(String fileUrl) throws Exception {
String key = extractS3KeyFromUrl(fileUrl);
File localFile = new File(GepafinConstant.TEMP_FILE_PATH + extractFileName(key));
String key = amazonS3Service.extractS3KeyFromUrl(fileUrl);
String fileName = extractFileName(key);
String folderPath = key.substring(0, key.lastIndexOf("/"));
File localFile = new File(GepafinConstant.TEMP_FILE_PATH + fileName);
GetObjectRequest getObjectRequest = new GetObjectRequest(OLD_BUCKET, key);
try (InputStream s3Stream = s3Client.getObject(getObjectRequest).getObjectContent(); FileOutputStream outputStream = new FileOutputStream(localFile)) {
try (InputStream s3Stream = amazonS3Service.getFile(folderPath, key); FileOutputStream outputStream = new FileOutputStream(localFile)) {
s3Stream.transferTo(outputStream);
}
@@ -992,11 +1172,6 @@ public class AppointmentDao {
return localFile;
}
private String extractS3KeyFromUrl(String url) {
return url.replace(s3Url, "");
}
private String extractFileName(String filePath) {
String[] parts = filePath.split("/");

View File

@@ -14,12 +14,14 @@ import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
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.AssignedApplicationViewResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.model.util.SortBy;
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
import net.gepafin.tendermanagement.repositories.AssignedApplicationsViewRepository;
import net.gepafin.tendermanagement.service.ApplicationService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.UserService;
@@ -77,13 +79,18 @@ public class AssignedApplicationsDao {
@Autowired
private ApplicationEvaluationRepository applicationEvaluationRepository;
@Autowired
private AssignedApplicationsViewRepository assignedApplicationsViewRepository;
public AssignedApplicationsResponse createAssignedApplications(Long applicationId, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest) {
log.info("Assigning application to pre-Instructor with details: {}", applicationId, userId);
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
if (assignedApplications != null && assignedApplications.getUserId().equals(userId)) {
log.warn("Application ID={} is already assigned to User ID={}", applicationId, userId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_ASSIGNED));
} else if(assignedApplications != null) {
log.info("Reassigning Application ID={} from User ID={} to User ID={}", applicationId, assignedApplications.getUserId(), userId);
assignedApplications = reassignApplication(userId, assignedByUser, assignedApplications);
AssignedApplicationsResponse assignApplicationToInstructorResponse = convertEntityToResponse(assignedApplications);
log.info("Application re-assigned succesfully {}", assignApplicationToInstructorResponse);
@@ -93,6 +100,7 @@ public class AssignedApplicationsDao {
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.SUBMIT.getValue().equals(application.getStatus()))) {
log.warn("Invalid application status for assignment. Application ID={}, Current Status={}", applicationId, application.getStatus());
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.INVALID_APPLICATION_STATUS)
@@ -101,6 +109,7 @@ public class AssignedApplicationsDao {
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(application);
application.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
applicationRepository.save(application);
log.info("Application status updated to EVALUATION for Application ID={}", applicationId);
/** This code is responsible for adding a version history log for the "Update Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEntity).newData(application).build());
@@ -115,7 +124,10 @@ public class AssignedApplicationsDao {
private AssignedApplicationsEntity reassignApplication(Long userId, UserEntity assignedByUser,
AssignedApplicationsEntity assignedApplication) {
log.info("Starting reassignment for AssignedApplication ID={}, from User ID={} to User ID={}, Assigned By User ID={}",
assignedApplication.getId(), assignedApplication.getUserId(), userId, assignedByUser.getId());
AssignedApplicationsEntity oldAssignedApplicationEntity = Utils.getClonedEntityForData(assignedApplication);
setIfUpdated(assignedApplication::getAssignedBy, assignedApplication::setAssignedBy, assignedByUser.getId());
@@ -130,11 +142,13 @@ public class AssignedApplicationsDao {
/** This code is responsible for adding a version history log for the "Create Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluationEntity).newData(entityOptional.get()).build());
log.info("Updated ApplicationEvaluationEntity for AssignedApplication ID={}", assignedApplication.getId());
};
assignedApplication = assignedApplicationsRepository.save(assignedApplication);
/** This code is responsible for adding a version history log for the "Create Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplicationEntity).newData(assignedApplication).build());
log.info("Reassignment completed for AssignedApplication ID={}, new User ID={}", assignedApplication.getId(), userId);
return assignedApplication;
}
@@ -215,8 +229,13 @@ public class AssignedApplicationsDao {
}
public AssignedApplicationsEntity validateAssignedApplication(Long id) {
AssignedApplicationsEntity assignedApplication = assignedApplicationsRepository.findByIdAndIsDeletedFalse(id).orElseThrow(() ->
new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_MSG)));
AssignedApplicationsEntity assignedApplication = assignedApplicationsRepository.findByIdAndIsDeletedFalse(id) .orElseThrow(() -> {
log.warn("AssignedApplication not found or deleted for ID: {}", id);
return new ResourceNotFoundException(
Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_MSG)
);
});
return assignedApplication;
}
@@ -227,11 +246,12 @@ public class AssignedApplicationsDao {
AssignedApplicationsEntity oldAssignedApplicationEntity = Utils.getClonedEntityForData(assignedApplicationsEntity);
assignedApplicationsEntity.setIsDeleted(true);
assignedApplicationsEntity = saveAssignedApplication(assignedApplicationsEntity, oldAssignedApplicationEntity, VersionActionTypeEnum.SOFT_DELETE);
log.info("Assigned Application deleted with ID: {}", id);
log.info("Soft-delete completed for AssignedApplication ID: {} by User ID: {}", id, assignedApplicationsEntity.getUserId());
}
public List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId,List<AssignedApplicationEnum> statusList) {
UserEntity user = validator.validateUser(request);
log.info("Fetching all assigned applications. Filtered target userId: {}", userId);
UserEntity user = validator.validateUser(request);
if(validator.checkIsPreInstructor() && userId == null) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.USER_ID_NOT_NULL_MSG));
}
@@ -297,7 +317,9 @@ public class AssignedApplicationsDao {
log.info("Assigned application fetched successfully: {}", response);
return response;
}
public PageableResponseBean<List<AssignedApplicationsResponse>> getAllAssignedApplicationsByPagination(UserEntity user, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,Long userId) {
public PageableResponseBean<List<AssignedApplicationViewResponse>> getAllAssignedApplicationsByPagination(UserEntity user, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,Long userId) {
log.info("Fetching assigned applications. Requestor: {}, Target User: {}", user.getId(), userId);
Integer pageNo = null;
Integer pageLimit = null;
if (assignedApplicationPageableRequestBean.getGlobalFilters() != null) {
@@ -310,21 +332,16 @@ public class AssignedApplicationsDao {
if (pageNo == null || pageNo <= 0) {
pageNo = GepafinConstant.DEFAULT_PAGE;
}
Specification<AssignedApplicationsEntity> spec = searchByPagination( assignedApplicationPageableRequestBean, user,userId);
Page<AssignedApplicationsEntity> entityPage = assignedApplicationsRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
Long hubId=user.getHub().getId();
Specification<AssignedApplicationsView> spec = searchByPagination( assignedApplicationPageableRequestBean,hubId,userId);
Page<AssignedApplicationsView> entityPage = assignedApplicationsViewRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
// Prepare the response
List<AssignedApplicationsResponse> assignedApplicationsResponses = entityPage.getContent().stream()
.map(application -> {
AssignedApplicationsResponse response = convertEntityToResponse(application);
return response;
})
List<AssignedApplicationViewResponse> assignedApplicationsResponses = entityPage.getContent().stream()
.map(this::getAssignedApplicationResponseByView)
.collect(Collectors.toList());
PageableResponseBean<List<AssignedApplicationsResponse>> pageableResponseBean = new PageableResponseBean<>();
PageableResponseBean<List<AssignedApplicationViewResponse>> pageableResponseBean = new PageableResponseBean<>();
pageableResponseBean.setBody(assignedApplicationsResponses);
pageableResponseBean.setCurrentPage(entityPage.getNumber() + 1);
pageableResponseBean.setTotalPages(entityPage.getTotalPages());
@@ -334,10 +351,10 @@ public class AssignedApplicationsDao {
return pageableResponseBean;
}
public Specification<AssignedApplicationsEntity> searchByPagination(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean, UserEntity userEntity,Long userId) {
public Specification<AssignedApplicationsView> searchByPagination(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean, Long hubId,Long userId) {
return (root, query, criteriaBuilder) -> {
List<Predicate> predicates = getPredicates(assignedApplicationPageableRequestBean, criteriaBuilder, root, userEntity,userId);
List<Predicate> predicates = getPredicates(assignedApplicationPageableRequestBean, criteriaBuilder, root, hubId,userId);
SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
if (assignedApplicationPageableRequestBean.getGlobalFilters() != null
@@ -350,30 +367,35 @@ public class AssignedApplicationsDao {
sortBy.setSortDesc(assignedApplicationPageableRequestBean.getGlobalFilters().getSortBy().getSortDesc());
}
}
Path<?> sortPath;
Join<AssignedApplicationsEntity, ApplicationEntity> applicationJoin = root.join(GepafinConstant.APPLICATION, JoinType.LEFT);
// Path<?> sortPath;
// Join<AssignedApplicationsEntity, ApplicationEntity> applicationJoin = root.join(GepafinConstant.APPLICATION, JoinType.LEFT);
//
// if (GepafinConstant.APPLICATION_ID.equals(sortBy.getColumnName())) {
// sortPath = root.join(GepafinConstant.APPLICATION, JoinType.LEFT).get(GepafinConstant.ID); // Join ApplicationEntity and sort by application.id
// }
// else if (GepafinConstant.PROTOCOL_NUMBER.equals(sortBy.getColumnName())) {
// Join<ApplicationEntity, ProtocolEntity> protocolJoin = applicationJoin.join(GepafinConstant.PROTOCOL, JoinType.LEFT);
// sortPath = protocolJoin.get(GepafinConstant.PROTOCOL_NUMBER);
// }
// else {
// sortPath = root.get(sortBy.getColumnName()); // Sorting by a field in AmendmentEntity
// }
// query.orderBy(criteriaBuilder.desc(sortPath));
// if (Boolean.FALSE.equals(sortBy.getSortDesc())) {
// query.orderBy(criteriaBuilder.asc(sortPath));
// }
// return query.where(criteriaBuilder.and(predicates.toArray(new Predicate[0]))).getRestriction();
Path<?> sortPath = root.get(sortBy.getColumnName()); // All fields are accessible directly in the view
query.orderBy(sortBy.getSortDesc() ? criteriaBuilder.desc(sortPath) : criteriaBuilder.asc(sortPath));
if (GepafinConstant.APPLICATION_ID.equals(sortBy.getColumnName())) {
sortPath = root.join(GepafinConstant.APPLICATION, JoinType.LEFT).get(GepafinConstant.ID); // Join ApplicationEntity and sort by application.id
}
else if (GepafinConstant.PROTOCOL_NUMBER.equals(sortBy.getColumnName())) {
Join<ApplicationEntity, ProtocolEntity> protocolJoin = applicationJoin.join(GepafinConstant.PROTOCOL, JoinType.LEFT);
sortPath = protocolJoin.get(GepafinConstant.PROTOCOL_NUMBER);
}
else {
sortPath = root.get(sortBy.getColumnName()); // Sorting by a field in AmendmentEntity
}
query.orderBy(criteriaBuilder.desc(sortPath));
if (Boolean.FALSE.equals(sortBy.getSortDesc())) {
query.orderBy(criteriaBuilder.asc(sortPath));
}
return query.where(criteriaBuilder.and(predicates.toArray(new Predicate[0]))).getRestriction();
};
}
private List<Predicate> getPredicates(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,
CriteriaBuilder criteriaBuilder, Root<AssignedApplicationsEntity> root, UserEntity userEntity,Long userId) {
CriteriaBuilder criteriaBuilder, Root<AssignedApplicationsView> root,Long hubId,Long userId) {
Integer year = null;
String search = null;
@@ -404,12 +426,35 @@ public class AssignedApplicationsDao {
}
// Search in `title` and `message` (if search term is provided)
if (search != null && !search.isEmpty()) {
Predicate titlePredicate = criteriaBuilder.like(
criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
"%" + search.toUpperCase() + "%"
);
predicates.add(criteriaBuilder.or(titlePredicate));
// if (search != null && !search.isEmpty()) {
// Predicate titlePredicate = criteriaBuilder.like(
// criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
// "%" + search.toUpperCase() + "%"
// );
// predicates.add(criteriaBuilder.or(titlePredicate));
// }
if (search != null && !search.trim().isEmpty()) {
String pattern = "%" + search.toUpperCase() + "%";
List<Predicate> searchPredicates = new ArrayList<>();
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.CALL_NAME)), pattern));
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.COMPANY_NAME)), pattern));
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.STATUS)), pattern));
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.NDG_STRING)), pattern));
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.APPOINTMENT_ID)), pattern));
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.APPLICATION_STATUS)), pattern));
// Convert numeric fields to string for search (optional and DB-specific; otherwise exact match)
try {
Long searchLong = Long.parseLong(search);
searchPredicates.add(criteriaBuilder.equal(root.get(GepafinConstant.APPLICATION_ID), searchLong));
searchPredicates.add(criteriaBuilder.equal(root.get(GepafinConstant.PROTOCOL_NUMBER), searchLong));
} catch (NumberFormatException ignored) {
// Ignore if search is not a number
}
predicates.add(criteriaBuilder.or(searchPredicates.toArray(new Predicate[0])));
}
// Filter by `status` (if status list is provided)
@@ -421,20 +466,45 @@ public class AssignedApplicationsDao {
}
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
applyFilters(root, criteriaBuilder, predicates, filters);
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.HUB_ID), hubId));
Utils.applyFiltersByPagination(root, criteriaBuilder, predicates, filters);
return predicates;
}
public AssignedApplicationsResponse updateAssignedApplicationStatus(HttpServletRequest request, Long assignedApplicationId, AssignedApplicationEnum status) {
private AssignedApplicationViewResponse getAssignedApplicationResponseByView(AssignedApplicationsView view) {
AssignedApplicationViewResponse response = new AssignedApplicationViewResponse();
response.setId(view.getId());
response.setUserId(view.getUserId());
response.setStatus(AssignedApplicationEnum.valueOf(view.getStatus()));
response.setApplicationId(view.getApplicationId());
response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(view.getApplicationStatus()));
response.setSubmissionDate(view.getSubmissionDate());
response.setEvaluationEndDate(view.getEvaluationEndDate());
response.setNdg(view.getNdg());
response.setAppointmentId(view.getAppointmentId());
response.setProtocolNumber(view.getProtocolNumber());
response.setCallName(view.getCallName());
response.setCompanyName(view.getCompanyName());
response.setCreatedDate(view.getCreatedDate());
response.setUpdatedDate(view.getUpdatedDate());
response.setEmailSendResponse(view.getEmailSendResponse());
return response;
}
public AssignedApplicationsResponse updateAssignedApplicationStatus(HttpServletRequest request, Long assignedApplicationId, AssignedApplicationEnum status) {
log.info("Request received to update status of assigned application. AssignedApplicationId: {}, NewStatus: {}", assignedApplicationId, status);
AssignedApplicationsEntity assignedApplication = validateAssignedApplication(assignedApplicationId);
validator.validatePreInstructor(request, assignedApplication.getUserId());
AssignedApplicationsEntity oldAssignedApplicationEntity = Utils.getClonedEntityForData(assignedApplication);
assignedApplication.setStatus(status.getValue());
AssignedApplicationsEntity updatedAssignment = saveAssignedApplication(assignedApplication, oldAssignedApplicationEntity, VersionActionTypeEnum.UPDATE);
log.info("Assigned application status updated successfully. AssignedApplicationId: {}, OldStatus: {}, NewStatus: {}",
assignedApplicationId, oldAssignedApplicationEntity.getStatus(), status.getValue());
return convertEntityToResponse(updatedAssignment);
}
private void applyFilters(Root<?> root, CriteriaBuilder criteriaBuilder, List<Predicate> predicates, Map<String, FilterCriteria> filters) {

View File

@@ -50,6 +50,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundExceptio
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.log;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.hibernate.internal.util.collections.CollectionHelper.listOf;
@@ -128,6 +129,7 @@ public class CallDao {
private ApplicationRepository applicationRepository;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
log.info("Starting Call creation - Step 1 by userId: {}", userEntity.getId());
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
@@ -136,12 +138,15 @@ public class CallDao {
CallResponse createCallResponseBean = getCallResponseBean(callEntity);
createCallResponseBean.setCurrentStep(GepafinConstant.STEP_1);
log.info("Call creation - Step 1 completed successfully for callId: {}", callEntity.getId());
return createCallResponseBean;
}
public byte[] downloadCallDocumentsAsZip(Long callId) {
log.info("Starting download of call documents as ZIP for callId: {}", callId);
List<DocumentEntity> documents = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callId, DocumentSourceTypeEnum.CALL.getValue(),DocumentTypeEnum.DOCUMENT.getValue());
if (documents.isEmpty()) {
log.warn("No documents found for callId: {}", callId);
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
}
@@ -149,6 +154,7 @@ public class CallDao {
ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
for (DocumentEntity document : documents) {
log.info("Adding document to ZIP: documentId={}, fileName={}", document.getId(), document.getFileName());
String s3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.CALL, callId, 0L,0L);
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFilePath())) {
String fileName = Utils.extractFileName(document.getFilePath());
@@ -157,14 +163,17 @@ public class CallDao {
IOUtils.copy(fileInputStream, zos);
zos.closeEntry();
} catch (IOException e) {
log.error("Error downloading or adding document to ZIP. documentId={}, fileName={}", document.getId(), document.getFileName(), e);
throw new RuntimeException("Error downloading or adding document to ZIP: " + document.getFileName(), e);
}
}
zos.finish();
log.info("Successfully created ZIP file for callId: {}", callId);
return zipOutputStream.toByteArray();
} catch (IOException e) {
log.error("Error while creating ZIP file for callId: {}", callId, e);
throw new RuntimeException("Error while creating ZIP file", e);
}
}
@@ -175,8 +184,11 @@ public class CallDao {
CallEntity callEntity = new CallEntity();
// validateCallEntity(createCallRequest);
RegionEntity region = regionRepository.findById(createCallRequest.getRegionId())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.REGION_NOT_FOUND)));
.orElseThrow(() -> {
log.error("Region not found for id: {}", createCallRequest.getRegionId());
return new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.REGION_NOT_FOUND));
});
callEntity.setRegion(region);
callEntity.setName(createCallRequest.getName());
callEntity.setDescriptionShort(createCallRequest.getDescriptionShort());
@@ -198,6 +210,7 @@ public class CallDao {
}
callEntity.setDocumentationRequested(createCallRequest.getDocumentationRequested());
if (createCallRequest.getAmountMin() != null && createCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) {
log.error("Invalid minimum amount: {}", createCallRequest.getAmountMin());
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG));
}
callEntity.setAmountMin(createCallRequest.getAmountMin());
@@ -212,6 +225,7 @@ public class CallDao {
callEntity.setNumberOfCheck(createCallRequest.getNumberOfCheck());
callEntity.setAppointmentTemplateId(createCallRequest.getAppointmentTemplateId());
callEntity = callRepository.save(callEntity);
log.info("CallEntity saved with ID: {} for call name: '{}'", callEntity.getId(), callEntity.getName());
/** This code is responsible for adding a version history log for the "Create Call" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(callEntity).build());
@@ -237,9 +251,11 @@ public class CallDao {
}
private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) {
log.info("Starting soft delete for EvaluationCriteriaEntity with ID: {}", evaluationCriteriaEntity.getId());
EvaluationCriteriaEntity oldEvaluationCriteriaEntity = Utils.getClonedEntityForData(evaluationCriteriaEntity);
evaluationCriteriaEntity.setIsDeleted(true);
evaluationCriteriaRepository.save(evaluationCriteriaEntity);
log.info("Soft deleted EvaluationCriteriaEntity with ID: {}", evaluationCriteriaEntity.getId());
/** This code is responsible for adding a version history log for the "soft delete evaluation criteria" operation **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldEvaluationCriteriaEntity).newData(evaluationCriteriaEntity).build());
@@ -256,8 +272,8 @@ public class CallDao {
/** This code is responsible for adding a version history log for the "soft delete criteria form field" operation **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldCriteriaFormFieldEntity).newData(data).build());
});
criteriaFormFieldRepository.saveAll(list);
criteriaFormFieldRepository.saveAll(list);
log.info("Soft deleted all linked CriteriaFormFieldEntity records for EvaluationCriteriaEntity ID: {}", evaluationCriteriaEntity.getId());
}
}
@@ -277,7 +293,7 @@ public class CallDao {
criteriaEntity = new EvaluationCriteriaEntity();
criteriaEntity.setCall(callEntity);
criteriaEntity.setLookupData(lookupDataEntity);
criteriaEntity.setScore(0L);
criteriaEntity.setScore(BigDecimal.ZERO);
criteriaEntity.setIsDeleted(false);
actionType = VersionActionTypeEnum.INSERT;
}
@@ -327,8 +343,11 @@ public class CallDao {
private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) {
validateDocumentEntity(documentReq.getId());
DocumentEntity documentEntity = documentRepository.findByIdAndSourceIdAndSourceAndIsDeletedFalse(documentReq.getId(),sourceId, DocumentSourceTypeEnum.CALL.getValue())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND)));
.orElseThrow(() -> {
log.error("Document not found or already deleted. Document ID: {}, Source ID: {}", documentReq.getId(), sourceId);
return new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
});
return documentEntity;
}
@@ -353,6 +372,7 @@ public class CallDao {
public void validateDocumentEntity(Long documentId) {
if (documentId == null || documentId < 1) {
log.warn("Invalid Document ID provided: {}", documentId);
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.DOCUMENT_ID_NOT_FOUND));
}
@@ -491,13 +511,16 @@ public class CallDao {
}
public CallEntity validateCall(Long callId) {
return callRepository.findById(callId).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)));
return callRepository.findById(callId).orElseThrow(() -> { log.error("Call not found for ID: {}", callId);
return new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
});
}
public CallResponse getCallById(HttpServletRequest request,UserEntity user, CallEntity callEntity, Long companyId) {
Long userId = user.getId();
Long callId = callEntity.getId();
log.info("Fetching Call details for Call ID: {}, User ID: {}, Company ID: {}", callId, userId, companyId);
BeneficiaryPreferredCallEntity preferredCall;
if (companyId != null) {
@@ -523,10 +546,13 @@ public class CallDao {
public CallResponse createCallStep2(CallEntity callEntity, CreateCallRequestStep2 createCallRequest, UserEntity user) {
// validateUpdate(callEntity);
log.info("Starting Call Step 2 update for Call ID: {}, User ID: {}", callEntity.getId(), user.getId());
if(createCallRequest.getThreshold() != null && Boolean.FALSE.equals(createCallRequest.getThreshold().equals(callEntity.getThreshold()))) {
CallEntity oldCallEntity = Utils.getClonedEntityForData(callEntity);
setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold());
callEntity = callRepository.save(callEntity);
log.info("Updated threshold for Call ID: {}", callEntity.getId());
/** This code is responsible for adding a version history log for the "update call step 2" operation **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCallEntity).newData(callEntity).build());
@@ -546,6 +572,7 @@ public class CallDao {
public void validateUpdate(CallEntity callEntity) {
if(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue())) {
log.warn("Attempted update on published call. Call ID: {}", callEntity.getId());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.PUBLISHED_CALL_NOT_UPDATE));
}
@@ -574,12 +601,14 @@ public class CallDao {
}
if (Boolean.FALSE.equals(isValid)) {
log.error("Invalid date range detected for Call ID: {}", callEntity.getId());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_DATE_MSG));
}
}
public CallResponse updateCallStep1(HttpServletRequest request,CallEntity callEntity, UpdateCallRequestStep1 updateCallRequest, UserEntity userEntity) {
log.info("Updating Call ID: {}, by User ID: {}", callEntity.getId(),userEntity.getId() );
CallEntity oldCallEntity = Utils.getClonedEntityForData(callEntity);
isValidDateRange(updateCallRequest, callEntity);
setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName());
@@ -639,9 +668,11 @@ public class CallDao {
updateCallRequest.getDocumentationRequested());
if (updateCallRequest.getAmountMin() != null && updateCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) {
log.error("Validation failed: Invalid email {} for Call ID: {}", updateCallRequest.getEmail(), callEntity.getId());
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG));
}
if(updateCallRequest.getEmail()!=null && Boolean.FALSE.equals(Utils.isValidEmail(updateCallRequest.getEmail()))){
log.error("Validation failed: Invalid email {} for Call ID: {}", updateCallRequest.getEmail(), callEntity.getId());
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,updateCallRequest.getEmail()));
}
setIfUpdated(callEntity::getAmountMin, callEntity::setAmountMin, updateCallRequest.getAmountMin());
@@ -661,6 +692,7 @@ public class CallDao {
updateFaq(updateCallRequest.getFaq(), callEntity, userEntity, LookUpDataTypeEnum.FAQ);
CallResponse createCallResponseBean = getCallResponseBean(callEntity);
createCallResponseBean.setCurrentStep(GepafinConstant.STEP_1);
log.info("Call Step 1 update completed for Call ID: {}", callEntity.getId());
return createCallResponseBean;
}
@@ -764,6 +796,7 @@ public class CallDao {
}
private CallResponse getCallResponseBean(CallEntity callEntity) {
log.info("Building CallResponse for Call ID: {}", callEntity.getId());
List<DocumentEntity> documentEntities = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callEntity.getId(),DocumentSourceTypeEnum.CALL.getValue()
, DocumentTypeEnum.DOCUMENT.getValue());
List<DocumentEntity> imageEntities = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callEntity.getId(), DocumentSourceTypeEnum.CALL.getValue()
@@ -790,6 +823,9 @@ public class CallDao {
public List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request,UserEntity user, Long companyId,Boolean onlyPreferredCall,Boolean onlyConfidiCall) {
String type = user.getRoleEntity().getRoleType();
log.info("Fetching calls for User ID: {}, Role: {}, Company ID: {}, onlyPreferredCall: {}, onlyConfidiCall: {}",
user.getId(), type, companyId, onlyPreferredCall, onlyConfidiCall);
List<String> callStatusList = CallStatusEnum.getStatusValues();
if (Boolean.FALSE.equals(ROLE_SUPER_ADMIN.getValue().equals(type))) {
callStatusList = List.of(CallStatusEnum.PUBLISH.getValue());
@@ -811,6 +847,7 @@ public class CallDao {
call.getEndDate() != null && call.getEndTime() != null) {
LocalDateTime callEndDateTime = LocalDateTime.of(LocalDate.from(call.getEndDate()), call.getEndTime());
if (callEndDateTime.isBefore(now)) {
log.info("Call ID: {} has expired. Updating status from PUBLISH to EXPIRED.", call.getId());
call.setStatus(CallStatusEnum.EXPIRED.getValue());
callRepository.save(call);
}
@@ -846,14 +883,17 @@ public class CallDao {
}
public Map<String, BeneficiaryPreferredCallEntity> getBeneficiaryPreferredCallsForUser(HttpServletRequest request, UserEntity user, List<Long> callIds, Long companyId) {
log.info("Fetching preferred calls for User ID: {}, Company ID: {}, Call IDs: {}", user.getId(), companyId, callIds);
List<BeneficiaryPreferredCallEntity> beneficiaryPreferredCalls;
if (companyId != null && (Boolean.TRUE.equals(validator.checkIsBeneficiary()) || Boolean.TRUE.equals(validator.checkIsConfidi()))) {
log.info("Validating user with company for preferred calls: User ID: {}, Company ID: {}", user.getId(), companyId);
validator.validateUserWithCompany(request, companyId);
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(user.getId(),companyId);
beneficiaryPreferredCalls = beneficiaryPreferredCallRepository
.findByUserIdAndCallIdInAndUserWithCompanyIdAndIsDeletedFalse(user.getId(), callIds, userWithCompanyEntity.getId());
} else {
log.info("Fetching preferred calls without company filtering for User ID: {}", user.getId());
beneficiaryPreferredCalls = beneficiaryPreferredCallRepository
.findByUserIdAndCallIdInAndIsDeletedFalse(user.getId(), callIds);
beneficiaryPreferredCalls = beneficiaryPreferredCalls.stream()
@@ -877,6 +917,7 @@ public class CallDao {
public CallResponse validateCallData(CallEntity callEntity) {
log.info("Starting call validation for Call ID: {}, Current Status: {}", callEntity.getId(), callEntity.getStatus());
CallEntity oldCallEntity = Utils.getClonedEntityForData(callEntity);
validateUpdate(callEntity);
CallResponse callResponseBean = getCallResponseBean(callEntity);
@@ -886,6 +927,7 @@ public class CallDao {
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean,evaluationFormResponseBean);
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
callEntity = callRepository.save(callEntity);
log.info("Call status updated to READY_TO_PUBLISH for Call ID: {}", callEntity.getId());
/** This code is responsible for adding a version history log for the "validate call" operation **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCallEntity).newData(callEntity).build());
@@ -903,11 +945,13 @@ public class CallDao {
// }
public CallResponse updateCallStatus(CallEntity callEntity, CallStatusEnum statusReq) {
log.info("Updating call status for Call ID: {} from {} to {}", callEntity.getId(), callEntity.getStatus(), statusReq);
CallEntity oldCallEntity = Utils.getClonedEntityForData(callEntity);
CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus());
validateStatusChange(currentStatus, statusReq, callEntity.getId());
callEntity.setStatus(statusReq.getValue());
callEntity = callRepository.save(callEntity);
log.info("Call status updated in DB for Call ID: {}. New Status: {}", callEntity.getId(), callEntity.getStatus());
//Creating notification.
List<Long> userIds = beneficiaryRepository.findUserIdsByHubIdAndBeneficiaryId(callEntity.getHub().getId());
@@ -926,27 +970,32 @@ public class CallDao {
}
private void validateStatusChange(CallStatusEnum currentStatus, CallStatusEnum newStatus, Long callId) {
log.info("Validating status change for Call ID: {} from '{}' to '{}'", callId, currentStatus, newStatus);
if (currentStatus == newStatus) {
log.warn("Validation failed: current status and new status are the same for Call ID: {}", callId);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.STATUS_SAME_ERROR));
}
switch (currentStatus) {
case DRAFT:
if (newStatus == CallStatusEnum.READY_TO_PUBLISH || newStatus == CallStatusEnum.PUBLISH) {
log.warn("Invalid status change attempt from DRAFT to {} for Call ID: {}", newStatus, callId);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_DRAFT));
}
break;
case PUBLISH:
if (newStatus == CallStatusEnum.READY_TO_PUBLISH) {
log.warn("Invalid status change attempt from PUBLISH to READY_TO_PUBLISH for Call ID: {}", callId);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_PUBLISH));
}
if (newStatus == CallStatusEnum.DRAFT && Boolean.TRUE.equals(applicationRepository.existsByCallId(callId))) {
log.warn("Invalid status change attempt from PUBLISH to DRAFT for Call ID: {} due to existing applications", callId);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_PUBLISH_TO_DRAFT));
}
break;
case EXPIRED:
log.warn("Attempt to change status from EXPIRED for Call ID: {} which is not allowed", callId);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.STATUS_CANNOT_BE_CHANGED));
case READY_TO_PUBLISH:
@@ -957,9 +1006,11 @@ public class CallDao {
}
public CallEntity validatePublishedCall(Long callId, Long hubId) {
log.info("Validating published call for Call ID: {}, Hub ID: {}", callId, hubId);
CallEntity callEntity= callRepository
.findByIdAndStatusAndHubId(callId, CallStatusEnum.PUBLISH.getValue(), hubId);
if(callEntity==null){
log.warn("No published call found with Call ID: {} and Hub ID: {}", callId, hubId);
throw new ResourceNotFoundException(
Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.CALL_NOT_PUBLISHED));
@@ -969,6 +1020,7 @@ public class CallDao {
if (currentDate.isBefore(callEntity.getStartDate().toLocalDate()) ||
(currentDate.isEqual(callEntity.getStartDate().toLocalDate()) && currentTime.isBefore(callEntity.getStartTime()))) {
log.warn("Call ID: {} has not started yet. Current time is before start time.", callId);
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.CALL_NOT_STARTED_YET)
@@ -977,6 +1029,7 @@ public class CallDao {
if (currentDate.isAfter(callEntity.getEndDate().toLocalDate()) ||
(currentDate.isEqual(callEntity.getEndDate().toLocalDate()) && currentTime.isAfter(callEntity.getEndTime()))) {
log.warn("Call ID: {} has already ended. Current time is after end time.", callId);
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.CALL_ALREADY_ENDED)
@@ -986,7 +1039,8 @@ public class CallDao {
return callEntity;
}
public PageableResponseBean<List<CallDetailsResponseBean>> getAllCallsByPagination(HttpServletRequest request,UserEntity user,Long companyId , Boolean onlyPreferredCall, CallPageableRequestBean callPageableRequestBean) {
public PageableResponseBean<List<CallDetailsResponseBean>> getAllCallsByPagination(HttpServletRequest request,UserEntity user,Long companyId , Boolean onlyPreferredCall, Boolean onlyConfidiCall, CallPageableRequestBean callPageableRequestBean) {
log.info("Fetching paginated calls for userId={}, companyId={}, onlyPreferredCall={}", user.getId(), companyId, onlyPreferredCall);
Integer pageNo = null;
Integer pageLimit = null;
if (callPageableRequestBean.getGlobalFilters() != null) {
@@ -1006,9 +1060,10 @@ public class CallDao {
);
}
expirePublishedCalls(request);
Specification<CallEntity> spec = search(request,user, callPageableRequestBean);
Specification<CallEntity> spec = search(request,user, callPageableRequestBean,onlyConfidiCall);
Page<CallEntity> entityPage;
if (Boolean.TRUE.equals(onlyPreferredCall)) {
log.debug("Filtering calls for preferred by userId={} and companyId={}", user.getId(), companyId);
validator.validateUserWithCompany(request, companyId);
UserWithCompanyEntity userWithCompanyEntity = companyService.getUserWithCompany(user.getId(), companyId);
List<BeneficiaryPreferredCallEntity> preferredCalls = beneficiaryPreferredCallRepository
@@ -1056,10 +1111,10 @@ public class CallDao {
return pageableResponseBean;
}
public Specification<CallEntity> search(HttpServletRequest request,UserEntity userEntity, CallPageableRequestBean callPageableRequestBean) {
public Specification<CallEntity> search(HttpServletRequest request,UserEntity userEntity, CallPageableRequestBean callPageableRequestBean,Boolean onlyConfidiCall) {
return (root, query, criteriaBuilder) -> {
List<Predicate> predicates = getPredicates(request,callPageableRequestBean, criteriaBuilder, root, userEntity);
List<Predicate> predicates = getPredicates(request,callPageableRequestBean, criteriaBuilder, root, userEntity,onlyConfidiCall);
SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
if (callPageableRequestBean.getGlobalFilters() != null
@@ -1083,7 +1138,7 @@ public class CallDao {
private List<Predicate> getPredicates(HttpServletRequest request,CallPageableRequestBean callPageableRequestBean,
CriteriaBuilder criteriaBuilder, Root<CallEntity> root, UserEntity userEntity) {
CriteriaBuilder criteriaBuilder, Root<CallEntity> root, UserEntity userEntity,Boolean onlyConfidiCall) {
Integer year = null;
String search = null;
Map<String, FilterCriteria> filters = new HashMap<>();
@@ -1137,7 +1192,7 @@ public class CallDao {
predicates.add(root.get(GepafinConstant.STATUS).in(statusValues));
}
applyFilters(root, criteriaBuilder, predicates, filters);
Boolean isConfidi = callPageableRequestBean.getConfidi();
Boolean isConfidi =onlyConfidiCall;
if (validator.checkIsConfidi()) {
@@ -1171,6 +1226,8 @@ public class CallDao {
LocalDate currentDate = DateTimeUtil.DateServerToUTC(LocalDateTime.now()).toLocalDate();
LocalTime currentTime = DateTimeUtil.LocalTimeServerToEurope(LocalTime.now());
log.info("Checking for expired published calls at date={}, time={}", currentDate, currentTime);
List<CallEntity> expirdedCallList = callRepository.findExpiredCallsWhichIsPublished(CallStatusEnum.PUBLISH.getValue(), currentDate, currentTime);
@@ -1321,7 +1378,7 @@ public class CallDao {
public CallResponse createCallStep2EvaluationV2(CallEntity callEntity, CreateCallRequestStep2EvaluationV2 createCallRequest, UserEntity user) {
log.info("Starting Step 2 Evaluation (V2) for Call ID={}, User ID={}", callEntity.getId(), user.getId());
convertToDocumentEntities(createCallRequest.getDocs(), callEntity.getId(), DocumentTypeEnum.DOCUMENT);
convertToDocumentEntities(createCallRequest.getImages(), callEntity.getId(), DocumentTypeEnum.IMAGES);

View File

@@ -52,13 +52,13 @@ public class CompanyDao {
private ApplicationRepository applicationRepository;
@Autowired
private FaqRepository faqRepository;
@Autowired
private BeneficiaryPreferredCallRepository beneficiaryPreferredCallRepository;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
@Autowired
private CompanyService companyService;
@@ -73,6 +73,7 @@ public class CompanyDao {
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
log.info("Initiating company creation by userId: {}", userEntity.getId());
CompanyEntity existingCompany = companyRepository.findByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId());
UserWithCompanyEntity userWithCompanyEntity = null;
if (existingCompany != null) {
@@ -84,6 +85,7 @@ public class CompanyDao {
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(userWithCompanyEntity).build());
} else {
log.warn("User already connected to company. userId: {}, companyId: {}", userEntity.getId(), existingCompany.getId());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY));
}
return convertCompanyEntityToCompanyResponse(existingCompany, userWithCompanyEntity);
@@ -103,7 +105,7 @@ public class CompanyDao {
private void validateCompany(UserEntity userEntity, CompanyRequest companyRequest) {
if (Boolean.FALSE.equals(StringUtils.isEmpty(companyRequest.getEmail()))
&& Boolean.FALSE.equals(Utils.isValidEmail(companyRequest.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
@@ -121,6 +123,7 @@ public class CompanyDao {
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity, Boolean isLegalRepresentant,CompanyRequest companyRequest) {
log.info("Creating user-company relation. userId: {}, companyId: {}, isLegalRep: {}", userEntity.getId(), companyEntity.getId(), isLegalRepresentant);
UserWithCompanyEntity userWithCompanyEntity = new UserWithCompanyEntity();
if (userEntity.getBeneficiary() != null) {
userWithCompanyEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
@@ -140,6 +143,7 @@ public class CompanyDao {
companyEntity.setJson(Utils.convertMapIntoJsonString(companyRequest.getVatCheckResponse()));
updateCodiceAtecoFieldWithNewJson(companyEntity);
companyEntity = companyRepository.save(companyEntity);
log.info("Updated company JSON field and saved. companyId: {}", companyEntity.getId());
/** This code is responsible for adding a version history log for "updating company json field" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder()
@@ -169,7 +173,7 @@ public class CompanyDao {
entity.setHub(userEntity.getHub());
entity.setJson(Utils.convertMapIntoJsonString(request.getVatCheckResponse()));
updateCodiceAtecoFieldWithNewJson(entity);
return entity;
}
@@ -202,6 +206,7 @@ public class CompanyDao {
public CompanyResponse updateCompany(UserEntity userEntity, Long companyId, CompanyRequest companyRequest) {
log.info("Updating company. companyId: {}, userId: {}", companyId, userEntity.getId());
CompanyEntity companyEntity = validateCompany(companyId);
//cloned entity for old data
CompanyEntity oldCompanyData = Utils.getClonedEntityForData(companyEntity);
@@ -226,11 +231,14 @@ public class CompanyDao {
//
// }
companyRepository.save(companyEntity);
log.info("Company updated and saved. companyId: {}", companyEntity.getId());
/** This code is responsible for adding a version history log for the "Update company" operation. **/
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCompanyData).newData(companyEntity).build());
log.info("Logged version history for company update. companyId: {}", companyEntity.getId());
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
//cloned entity for old data
UserWithCompanyEntity oldUserWithCompanyData = Utils.getClonedEntityForData(userWithCompanyEntity);
@@ -253,17 +261,19 @@ public class CompanyDao {
}
public CompanyEntity validateCompany(Long companyId) {
log.info("Validating company. companyId: {}", companyId);
return companyRepository.findById(companyId).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.COMPANY_NOT_FOUND_MSG)));
}
public CompanyResponse getCompany(UserEntity userEntity, Long companyId) {
log.info("Fetching company details. userId: {}, companyId: {}", userEntity.getId(), companyId);
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
return convertCompanyEntityToCompanyResponse(validateCompany(companyId), userWithCompanyEntity);
}
public void deleteCompany(UserEntity userEntity, Long companyId) {
log.info("Deleting company. userId: {}, companyId: {}", userEntity.getId(), companyId);
CompanyEntity companyEntity = validateCompany(companyId);
/** This code is responsible for adding a version history log for the "delete company" operation. **/
@@ -281,6 +291,7 @@ public class CompanyDao {
}
public List<CompanyResponse> getCompanyByUserId(Long userId) {
log.info("Fetching companies by userId: {}", userId);
UserEntity userEntity = userService.validateUser(userId);
List<Long> activeCompanyIds = userWithCompanyRepository.findActiveCompanyIdsByUserId(userEntity.getId());
List<CompanyEntity> companies = companyRepository.findByIdInAndHubId(activeCompanyIds, userEntity.getHub().getId());
@@ -291,15 +302,18 @@ public class CompanyDao {
}
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
log.info("Validating user-company access. userId: {}, companyId: {}", userId, companyId);
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
}
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
log.info("Fetching user-company relation. userId: {}, companyId: {}", userId, compnayId);
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, compnayId).orElseThrow(
() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_COMPANY_RELATION_NOT_FOUND)));
}
public void removeCompanyFromList(UserEntity userEntity, Long companyId) {
log.info("Initiating removal of company from user list. userId: {}, companyId: {}", userEntity.getId(), companyId);
CompanyEntity companyEntity = validateCompany(companyId);
UserWithCompanyEntity existingRelation=companyService.getUserWithCompany(userEntity.getId(),companyEntity.getId());
List<ApplicationEntity> userApplications = applicationRepository.findByUserWithCompanyIdAndUserIdAndIsDeletedFalse(existingRelation.getId(), userEntity.getId());
@@ -314,6 +328,7 @@ public class CompanyDao {
boolean notAllowedStatus = userApplications.stream()
.anyMatch(application -> !applicationStatusAllowed.contains(application.getStatus()));
if (notAllowedStatus) {
log.warn("Cannot remove company. One or more applications in non-removable status. userId: {}, companyId: {}", userEntity.getId(), companyId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT));
}
@@ -483,12 +498,19 @@ public class CompanyDao {
return;
}
Object pecEmailObj = dettaglio.get("pec");
if (pecEmailObj instanceof String pec && !pec.isEmpty()) {
company.setPec(pec); // Only set if valid string
} else {
log.warn("Company ID {}: 'pec' is missing, empty, or not a string.", company.getId());
}
Object codiceAtecoObj = dettaglio.get("codice_ateco");
if (!(codiceAtecoObj instanceof String codiceAteco) || codiceAteco.isEmpty()) {
log.warn("Company ID {}: 'codice_ateco' is missing, empty, or not a string.", company.getId());
return;
}
company.setCodiceAteco(codiceAteco);
logCodiceAtecoUpdate(company, codiceAteco);
}
@@ -517,6 +539,13 @@ public class CompanyDao {
// if data is a single object
updateCodiceAtecoField(company);
} else {
Object pecEmail = Utils.extractMap(dataMap, "pec");
if (pecEmail == null) {
log.warn("Company ID {}: 'pec' section is missing or invalid.", company.getId());
company.setPec((String) pecEmail);
}
// Extract 'atecoClassification' section
Map<String, Object> atecoClassificationMap = Utils.extractMap(dataMap, "atecoClassification");
if (atecoClassificationMap == null) {
@@ -546,4 +575,51 @@ public class CompanyDao {
log.info("Company ID {}: codiceAteco updated to {}", company.getId(), atecoCode);
}
public void getCompanyEntity() {
List<CompanyEntity> companyEntities=companyRepository.findAll();
for (CompanyEntity company:companyEntities){
if(company.getJson()!=null){
if (company == null || company.getJson() == null || company.getJson().isEmpty()) {
log.warn("Company is null or JSON data is empty.");
return;
}
Map<String, Object> vatCheckResponse = Utils.convertJsonStringToMap(company.getJson());
if (vatCheckResponse == null) {
log.warn("Company ID {}: Invalid JSON response.", company.getId());
return;
}
Map<String, Object> companyDataMap = Utils.convertJsonStringToMap(company.getJson());
if (companyDataMap == null) {
log.warn("Company ID {}: Failed to parse JSON data.", company.getId());
return;
}
Object dataObj = vatCheckResponse.get("data");
if (!(dataObj instanceof Map<?, ?> dataMap)) {
log.warn("Company ID {}: 'data' is missing or not a valid object.", company.getId());
return;
}
if (!dataMap.containsKey("dettaglio")) {
log.warn("Company ID {}: 'dettaglio' not present inside 'data'. Skipping codiceAteco update.", company.getId());
return;
}
Object dettaglioObj = dataMap.get("dettaglio");
if (!(dettaglioObj instanceof Map<?, ?> dettaglio)) {
log.warn("Company ID {}: 'dettaglio' is not a valid object.", company.getId());
return;
}
Object pecEmailObj = dettaglio.get("pec");
if (pecEmailObj instanceof String pec && !pec.isEmpty()) {
company.setPec(pec); // Only set if valid string
} else {
log.warn("Company ID {}: 'pec' is missing, empty, or not a string.", company.getId());
}
}
}
}
}

View File

@@ -92,16 +92,20 @@ public class CompanyDocumentDao {
private AmazonS3 amazonS3;
public List<CompanyDocumentResponseBean> uploadFileForCompany(HttpServletRequest request, Long userId, List<MultipartFile> files, Long companyId, Long documentCategoryId, CompanyDocumentTypeEnum companyDocumentSourceTypeEnum, LocalDateTime expirationDate,String name){
log.info("Uploading files for company. userId={}, companyId={}, documentCategoryId={}", userId, companyId, documentCategoryId);
DocumentCategoryEntity categoryEntity = categoryDao.validateCategory(documentCategoryId);
validator.validateUserWithCompany(request,companyId);
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userId,companyId);
LocalDateTime currentDate = LocalDateTime.now();
if (expirationDate.isBefore(currentDate)) {
log.warn("Expiration date {} is before current time {}", expirationDate, currentDate);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_EXPIRATION_DATE));
}
List<CompanyDocumentEntity> companyDocumentEntities = new ArrayList<>();
for (MultipartFile file : files){
log.info("Uploading file '{}' for companyId={}", file.getOriginalFilename(), companyId);
UploadFileOnAmazonS3Response uploadFileOnAmazonS3Response = uploadFileOnAmazonS3(file, companyDocumentSourceTypeEnum, companyId);
if (uploadFileOnAmazonS3Response != null) {
CompanyDocumentEntity companyDocumentEntity = new CompanyDocumentEntity();
@@ -114,8 +118,10 @@ public class CompanyDocumentDao {
companyDocumentEntity.setName(name);
if (expirationDate.isBefore(currentDate.plusDays(7))) {
companyDocumentEntity.setStatus(CompanyDocumentStatusEnum.DUE.getValue());
log.info("Document '{}' marked as DUE (expires within 7 days).", uploadFileOnAmazonS3Response.getFileName());
} else {
companyDocumentEntity.setStatus(CompanyDocumentStatusEnum.VALID.getValue());
log.info("Document '{}' marked as VALID.", uploadFileOnAmazonS3Response.getFileName());
}
companyDocumentEntity.setCategoryEntity(categoryEntity);
@@ -125,9 +131,9 @@ public class CompanyDocumentDao {
}
}
companyDocumentRepository.saveAll(companyDocumentEntities);
log.info("Saved {} documents for companyId={}", companyDocumentEntities.size(), companyId);
/** This code is responsible for adding a version history log for the "Upload company document" operation. **/
companyDocumentEntities.forEach(entity -> loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(entity).build()));
@@ -143,6 +149,7 @@ public class CompanyDocumentDao {
log.info("Generated S3 path {}", s3Path);
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
} catch (Exception e) {
log.error("Error occurred while uploading file '{}' for Company ID '{}': {}", file.getOriginalFilename(), companyId, e.getMessage());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
}
@@ -151,13 +158,17 @@ public class CompanyDocumentDao {
try {
return s3ConfigBean.generateCompanyDocumentPath(typeOfDocument, companyId);
} catch (IllegalArgumentException e) {
log.error("Failed to generate S3 path for Company ID '{}' and Document Type '{}': {}", companyId, typeOfDocument, e.getMessage());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
}
}
public CompanyDocumentEntity validateCompanyDocument(Long id) {
return companyDocumentRepository.findByIdAndNotDeleted(id).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.COMPANY_DOCUMENT_NOT_FOUND)));
return companyDocumentRepository.findByIdAndNotDeleted(id).orElseThrow(() -> {
log.warn("Company Document not found with ID '{}'", id);
return new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.COMPANY_DOCUMENT_NOT_FOUND));
});
}
public CompanyDocumentResponseBean convertToCompanyDocumentResponseBean(CompanyDocumentEntity entity) {
@@ -182,20 +193,23 @@ public class CompanyDocumentDao {
}
public CompanyDocumentResponseBean updateCompanyDocument(HttpServletRequest request,Long companyDocumentId, CompanyDocumentRequest companyDocumentRequest){
log.info("Start: Updating company document with ID: {}", companyDocumentId);
CompanyDocumentEntity companyDocumentEntity = validateCompanyDocument(companyDocumentId);
validator.validateUserWithCompany(request,companyDocumentEntity.getCompanyId());
CompanyDocumentEntity oldCompanyDocumentData = Utils.getClonedEntityForData(companyDocumentEntity);
LocalDateTime currentDate = LocalDateTime.now();
if (companyDocumentRequest.getExpirationDate() != null) {
if (companyDocumentRequest.getExpirationDate().isBefore(currentDate)) {
log.warn("Invalid expiration date: {}", companyDocumentRequest.getExpirationDate());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_EXPIRATION_DATE));
}
companyDocumentEntity.setExpirationDate(companyDocumentRequest.getExpirationDate());
if (companyDocumentRequest.getExpirationDate().isBefore(currentDate.plusDays(7))) {
companyDocumentEntity.setStatus(CompanyDocumentStatusEnum.DUE.getValue());
log.info("Document '{}' marked as DUE.", companyDocumentEntity.getName());
} else {
companyDocumentEntity.setStatus(CompanyDocumentStatusEnum.VALID.getValue());
log.info("Document '{}' marked as VALID (expiration is beyond 7 days).", companyDocumentEntity.getName());
}
}
if (companyDocumentRequest.getCategoryId() != null && companyDocumentRequest.getCategoryId() >0) {
@@ -204,6 +218,7 @@ public class CompanyDocumentDao {
}
setIfUpdated(companyDocumentEntity::getName, companyDocumentEntity::setName, companyDocumentRequest.getName());
companyDocumentRepository.save(companyDocumentEntity);
log.info("Saved updates for Company Document ID '{}'", companyDocumentId);
/** This code is responsible for adding a version history log for the "updating company document" operation. **/
loggingUtil.addVersionHistory(
@@ -213,12 +228,14 @@ public class CompanyDocumentDao {
}
public CompanyDocumentResponseBean getCompanyDocument(UserEntity user ,Long companyDocumentId) {
log.info("Fetching company document with ID '{}' for user '{}'", companyDocumentId, user.getId());
CompanyDocumentEntity companyDocumentEntity = validateCompanyDocument(companyDocumentId);
validator.validateUserWithCompany(request,companyDocumentEntity.getCompanyId());
return convertToCompanyDocumentResponseBean(companyDocumentEntity);
}
public void deleteCompanyFile(Long companyDocumentId){
log.info("Deleting file for company document ID '{}'", companyDocumentId);
CompanyDocumentEntity companyDocumentEntity = validateCompanyDocument(companyDocumentId);
deleteCompanyFileFromS3(companyDocumentEntity);
}
@@ -259,6 +276,7 @@ public class CompanyDocumentDao {
}
public DocumentResponseBean createDuplicateCompanyDocument(HttpServletRequest request , Long userId ,Long companyDocumentId , Long applicationId , DocumentTypeEnum documentTypeEnum){
log.info("Creating duplicate of company document ID '{}' for application ID '{}'", companyDocumentId, applicationId);
ApplicationEntity applicationEntity = applicationService.validateApplication(applicationId);
CompanyDocumentEntity companyDocumentEntity = validateCompanyDocument(companyDocumentId);
validator.validateUserWithCompany(request,companyDocumentEntity.getCompanyId());
@@ -272,7 +290,7 @@ public class CompanyDocumentDao {
try {
response = amazonS3ServiceImpl.copyFile(companyDocumentEntity.getName(), companyDocumentPath, documentPath);
} catch (Exception e) {
log.error("Error occurred while uploading file from Amazon S3: {}", e);
log.error("Error occurred while uploading file from Amazon S3: {} for application ID '{}' and company Document ID '{}' ", e,applicationId,companyDocumentId);
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
@@ -296,12 +314,14 @@ public class CompanyDocumentDao {
}
public List<CompanyDocumentResponseBean> getAllCompanyDocument(UserEntity user , Long companyId, CompanyDocumentTypeEnum typeEnum){
log.info("Fetching all company documents for Company ID '{}', User ID '{}', Type '{}'", companyId, user.getId(), typeEnum);
validator.validateUserWithCompany(request, companyId);
companyService.validateCompany(companyId);
Specification<CompanyDocumentEntity> spec = filterCompanyDocuments(companyId, user.getId(), typeEnum);
List<CompanyDocumentEntity> companyDocumentEntities = companyDocumentRepository.findAll(spec);
log.info("Retrieved all documents for Company ID '{}'", companyId);
return companyDocumentEntities.stream()
.map(this::convertToCompanyDocumentResponseBean)
.collect(Collectors.toList());

View File

@@ -82,10 +82,11 @@ public class DocumentDao {
// private String s3Folder;
public List<DocumentResponseBean> uploadFiles(Long userId,List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
log.info("Uploading files userId={}, sourceType={}, fileType={}", userId,sourceType,fileType);
List<DocumentEntity> documentEntities = new ArrayList<>();
Long source = resolveSourceId(sourceId, sourceType);
for (MultipartFile file : files) {
log.info("Uploading file '{}'", file.getOriginalFilename());
UploadFileOnAmazonS3Response uploadFileOnAmazonS3Response = uploadFileOnAmazonS3(file, sourceType, sourceId);
if (uploadFileOnAmazonS3Response != null) {
DocumentEntity documentEntity = new DocumentEntity();
@@ -148,6 +149,7 @@ public class DocumentDao {
private UploadFileOnAmazonS3Response uploadFileOnAmazonS3(MultipartFile file, DocumentSourceTypeEnum type, Long sourceId) {
log.info("Starting S3 upload: fileName={}, documentType={}, sourceId={}", file.getOriginalFilename(), type, sourceId);
Long applicationId = 0L;
Long amendmentId = 0L;
Long evaluationId = 0L;
@@ -155,26 +157,32 @@ public class DocumentDao {
if (type == DocumentSourceTypeEnum.APPLICATION) {
applicationId = sourceId;
callId = applicationRepository.findCallIdById(applicationId);
log.info("Processing document of type APPLICATION .Resolved applicationId={}, callId={}", applicationId, callId);
} else if (type == DocumentSourceTypeEnum.AMENDMENT) {
amendmentId = sourceId;
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type AMENDMENT .Resolved amendmentId={}, applicationId={}, callId={}", amendmentId, applicationId, callId);
}else if (type == DocumentSourceTypeEnum.EVALUATION) {
evaluationId = sourceId;
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type EVALUATION .Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId);
}
try {
String s3Path = generateS3Path(type, callId, applicationId, amendmentId);
log.info("Generated S3 path {}", s3Path);
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
} catch (Exception e) {
log.error("Error uploading file to S3: fileName={}, documentType={}, sourceId={}, error={}",
file.getOriginalFilename(), type, sourceId, e.getMessage(), e);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
}
public String generateS3Path(DocumentSourceTypeEnum typeOfDocument, Long callId, Long applicationId, Long amendmentId) {
try {
return s3ConfigBean.generateDocumentPath(typeOfDocument, callId, applicationId, amendmentId);
@@ -202,6 +210,7 @@ public class DocumentDao {
DocumentEntity documentEntity = documentRepository.findById(documentId).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND)));
if(Boolean.TRUE.equals(documentEntity.getIsDeleted())){
log.info("Document with id={} is already marked as deleted. Skipping deletion.", documentId);
return;
}
Long callId = null;
@@ -211,24 +220,28 @@ public class DocumentDao {
if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(documentEntity.getSource())) {
callId = documentEntity.getSourceId();
log.info("Processing document of type CALL. Resolved callId={}", callId);
} else if (DocumentSourceTypeEnum.APPLICATION.getValue().equalsIgnoreCase(documentEntity.getSource())) {
applicationId = documentEntity.getSourceId();
ApplicationEntity applicationEntity = applicationService.validateApplication(applicationId);
callId = applicationEntity.getCall().getId();
log.info("Processing document of type APPLICATION. Resolved applicationId={}, callId={}", applicationId, callId);
}
else if(DocumentSourceTypeEnum.AMENDMENT.getValue().equalsIgnoreCase(documentEntity.getSource())){
amendmentId = documentEntity.getSourceId();
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type AMENDMENT. Resolved amendmentId={}, applicationId={}, callId={}", amendmentId, applicationId, callId);
} else if(DocumentSourceTypeEnum.EVALUATION.getValue().equalsIgnoreCase(documentEntity.getSource())){
evaluationId = documentEntity.getSourceId();
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type EVALUATION. Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId);
}
deleteFileFromS3(documentEntity, callId, applicationId,amendmentId);
log.info("Successfully deleted file from S3 for documentId={}", documentId);
}
public DocumentEntity validateDocument(Long id) {
@@ -238,6 +251,9 @@ public class DocumentDao {
public DocumentResponseBean updateDocument(Long documentId, MultipartFile file, DocumentTypeEnum documentTypeEnum) {
log.info("Starting document update: documentId={} , newDocumentType={}",
documentId , documentTypeEnum);
DocumentEntity documentEntity = validateDocument(documentId);
//cloned entity for old data
DocumentEntity oldDocumentData = Utils.getClonedEntityForData(documentEntity);
@@ -245,12 +261,15 @@ public class DocumentDao {
String type = documentEntity.getSource();
UploadFileOnAmazonS3Response uploadFileOnAmazonS3Response = updateFileOnAmazonS3(file, DocumentSourceTypeEnum.valueOf(type), documentEntity.getSourceId());
if (uploadFileOnAmazonS3Response != null) {
log.info("Successfully uploaded new file to S3: fileName={}",
uploadFileOnAmazonS3Response.getFileName());
documentEntity.setFileName(uploadFileOnAmazonS3Response.getFileName());
documentEntity.setFilePath(uploadFileOnAmazonS3Response.getFilePath());
documentEntity.setType(documentTypeEnum.getValue());
documentEntity.setSource(documentEntity.getSource());
documentEntity.setSourceId(documentEntity.getSourceId());
documentRepository.save(documentEntity);
log.info("Document updated in database for documentId={}", documentId);
/** This code is responsible for adding a version history log for the "updating doc or image" operation. **/
loggingUtil.addVersionHistory(
@@ -260,7 +279,6 @@ public class DocumentDao {
}
private UploadFileOnAmazonS3Response updateFileOnAmazonS3(MultipartFile file, DocumentSourceTypeEnum type, Long id) {
try {
Long callId=null;
Long applicationId=null;
@@ -269,27 +287,32 @@ public class DocumentDao {
if (type.equals(DocumentSourceTypeEnum.APPLICATION)) {
callId = applicationRepository.findCallIdById(id);
applicationId = id;
log.info("Processing document of type APPLICATION . Resolved applicationId={}, callId={}", applicationId, callId);
}
else if(type.equals(DocumentSourceTypeEnum.AMENDMENT)){
amendmentId = id;
ApplicationEntity applicationEntity = applicationAmendmentRequestRepository.findApplicationByAmendmentId(amendmentId);
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type AMENDMENT . Resolved amendmentId={}, applicationId={}, callId={}", amendmentId, applicationId, callId);
}else if(type.equals(DocumentSourceTypeEnum.EVALUATION)){
evaluationId = id;
ApplicationEntity applicationEntity = applicationEvaluationRepository.findApplicationByEvaluationId(evaluationId);
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type EVALUATION . Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId);
}
else {
callId = id;
applicationId = 0L;
log.info("Processing document of type CALL . Resolved callId={}", callId);
}
String s3Path = generateS3Path(type, callId, applicationId,amendmentId);
log.info("Generated S3 path {}", s3Path);
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
} catch (Exception e) {
log.error("Error during file update to S3: documentType={}, sourceId={}, error={}",type, id, e.getMessage(), e);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
}
@@ -304,6 +327,7 @@ public class DocumentDao {
DocumentEntity oldDocumentEntity = Utils.getClonedEntityForData(documentEntity);
String oldS3Path = documentEntity.getFilePath();
String newS3Path = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.valueOf("DELETED_" + documentEntity.getSource().toUpperCase()), callId, applicationId,amendmentId);
log.info("Moving file to deleted path: oldS3Path={}, newS3Path={}", oldS3Path, newS3Path);
UploadFileOnAmazonS3Response response = amazonS3Service.moveFile(documentEntity.getFileName(), oldS3Path, newS3Path);
documentEntity.setFileName(response.getFileName());
documentEntity.setFilePath(response.getFilePath());

View File

@@ -0,0 +1,212 @@
package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum;
import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.RecipientTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.model.response.EmailResendResponseBean;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Utils;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
@Log4j2
public class EmailDao {
@Autowired
EmailLogRepository emailLogRepository;
@Autowired
EmailNotificationDao emailNotificationDao;
@Autowired
private CallService callService;
@Autowired
private EmailLogDao emailLogDao;
@Autowired
private UserActionsRepository userActionsRepository;
@Autowired
private ApplicationAmendmentRequestRepository applicationAmendmentRequestRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ApplicationEvaluationRepository applicationEvaluationRepository;
public EmailResendResponseBean resendEmail(HttpServletRequest request , Long userActionId){
UserActionEntity userActionEntity = userActionsRepository.findUserActionByIdAndIsDeletedFalse(userActionId);
if(userActionEntity == null){
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_ACTION_ID_NOT_FOUND));
}
List<EmailLogEntity> emailLogs = emailLogRepository.findByUserActionIdAndEmailServiceTypeAndSendStatus(userActionId,EmailServiceTypeEnum.PEC_SERVICE.getValue(),StatusTypeEnum.FAILED.getValue());
if (emailLogs.isEmpty()) {
log.info("No emails found for given userActionId: {}",userActionId);
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.NO_EMAIL_LOG_FOUND));
}
EmailResendResponseBean emailResendResponseBean = new EmailResendResponseBean();
for (EmailLogEntity log : emailLogs){
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(EmailScenarioTypeEnum.valueOf(log.getEmailType()),
RecipientTypeEnum.valueOf(log.getRecipientType()),
log.getRecipientId(),
log.getRecipientEmails(),
log.getUserId(),
log.getApplicationId(),
log.getAmendmentId(),
log.getCallId()
);
List<String> recipients = Utils.commaSeparatedStringToList(log.getRecipientEmails());
CallEntity call = callService.validateCall(log.getCallId());
emailNotificationDao.sendMail(
call.getHub().getId(),
log.getEmailSubject(),
log.getEmailBody(),
recipients,
emailLogRequest
);
}
EmailSendResponse emailSendResponse = buildEmailSendResponseFromRequest(request);
emailResendResponseBean.setEmailSendResponse(emailSendResponse);
if (Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
updateEmailSendStatusIfSuccessful(emailSendResponse);
}
return emailResendResponseBean;
}
private void updateEmailSendStatusIfSuccessful(EmailSendResponse emailSendResponse){
Long actionId = emailSendResponse.getUserActionId();
EmailLogEntity emailLog = emailLogRepository.findTopByUserActionIdAndEmailServiceTypeAndSendStatusOrderByIdDesc(
actionId,
EmailServiceTypeEnum.PEC_SERVICE.getValue(),
StatusTypeEnum.SUCCESS.getValue()
);
if (emailLog != null) {
switch (emailSendResponse.getEmailScenario()) {
case APPLICATION_AMENDMENT_REQUESTED:
case APPLICATION_AMENDMENT_REMINDER:
updateApplicationAmendmentStatus(emailLog, emailSendResponse.getEmailScenario().getValue());
break;
case USER_CREATION:
case PASSWORD_RESET_REQUEST:
updateUserEmailStatus(emailLog, emailSendResponse.getEmailScenario().getValue());
break;
case APPLICATION_ADMISSIBLE:
case APPLICATION_REJECTED:
updateApplicationEvaluationStatus(emailLog, emailSendResponse.getEmailScenario().getValue());
break;
default:
log.warn("Unhandled email scenario: {}", emailSendResponse.getEmailScenario());
}
}
}
private void updateApplicationAmendmentStatus(EmailLogEntity log, String scenario) {
if (log.getAmendmentId() != null) {
applicationAmendmentRequestRepository.findById(log.getAmendmentId()).ifPresent(amendment -> {
if (updateEmailSendResponse(amendment.getEmailSendResponse(), scenario)) {
applicationAmendmentRequestRepository.save(amendment);
}
});
}
}
private void updateApplicationEvaluationStatus(EmailLogEntity log, String scenario) {
if (log.getApplicationId() != null) {
ApplicationEvaluationEntity evaluation = applicationEvaluationRepository.findByApplicationId(log.getApplicationId());
if (evaluation != null && updateEmailSendResponse(evaluation.getEmailSendResponse(), scenario)) {
applicationEvaluationRepository.save(evaluation);
}
}
}
private void updateUserEmailStatus(EmailLogEntity log, String scenario) {
if (log.getUserId() != null) {
userRepository.findById(log.getUserId()).ifPresent(user -> {
if (updateEmailSendResponse(user.getEmailSendResponse(), scenario)) {
userRepository.save(user);
}
});
}
}
private boolean updateEmailSendResponse(List<EmailSendResponse> responses, String scenario) {
if (responses == null || responses.isEmpty()) return false;
for (Iterator<EmailSendResponse> iterator = responses.iterator(); iterator.hasNext(); ) {
EmailSendResponse response = iterator.next();
if (scenario.equals(response.getEmailScenario().getValue())) {
iterator.remove(); // remove only the first match
return true;
}
}
return false;
}
public EmailSendResponse buildEmailSendResponseFromRequest(HttpServletRequest request) {
Long userActionId = (Long) request.getAttribute(GepafinConstant.USER_ACTION_ID);
List<EmailLogEntity> emailLogs = emailLogRepository.findByUserActionIdAndEmailServiceType(userActionId,EmailServiceTypeEnum.PEC_SERVICE.getValue());
boolean allSuccess = true;
String emailScenario = null;
for (EmailLogEntity log : emailLogs) {
if (emailScenario == null) {
emailScenario = log.getEmailType();
}
boolean isSuccess = StatusTypeEnum.SUCCESS.getValue().equals(log.getSendStatus());
if (Boolean.FALSE.equals(isSuccess)) {
allSuccess = false;
break;
}
}
return buildResponse(userActionId, allSuccess, emailScenario);
}
private EmailSendResponse buildResponse(Long userActionId, boolean allSuccess, String emailScenario) {
EmailSendResponse response = new EmailSendResponse();
response.setUserActionId(userActionId);
response.setIsEmailSend(allSuccess);
response.setEmailScenario(emailScenario != null ? EmailScenarioTypeEnum.valueOf(emailScenario) : null);
return response;
}
}

View File

@@ -1,6 +1,7 @@
package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum;
import net.gepafin.tendermanagement.enums.EmailEntityTypeEnum;
@@ -9,6 +10,7 @@ import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.repositories.UserActionsRepository;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.LoggingUtil;
import org.springframework.beans.factory.annotation.Autowired;
@@ -22,6 +24,12 @@ public class EmailLogDao {
@Autowired
private EmailLogRepository emailLogRepository;
@Autowired
private HttpServletRequest request;
@Autowired
private LoggingUtil loggingUtil;
public EmailLogEntity createEmailLog(EmailLogRequest emailLogRequest) {
@@ -42,8 +50,8 @@ public class EmailLogDao {
emailLogEntity.setApplicationId(emailLogRequest.getApplicatioId());
emailLogEntity.setAmendmentId(emailLogRequest.getAmendmentId());
emailLogEntity.setCallId(emailLogRequest.getCallId());
emailLogEntity.setUserAction(loggingUtil.getUserActionLogById(emailLogRequest.getUserActionId()));
emailLogEntity = saveEmailLogEntity(emailLogEntity);
return emailLogEntity;
}
public EmailLogEntity saveEmailLogEntity(EmailLogEntity emailLogEntity){
@@ -52,6 +60,7 @@ public class EmailLogDao {
public EmailLogRequest createEmailLogRequest(EmailScenarioTypeEnum emailType, RecipientTypeEnum recipientType, Long recipientId,
String recipientEmails, Long userId,Long applicationId,Long amendmentId,Long callId) {
EmailLogRequest emailLogRequest = new EmailLogRequest();
Long userActionId =(Long) request.getAttribute(GepafinConstant.USER_ACTION_ID);
emailLogRequest.setEmailType(emailType);
emailLogRequest.setRecipientType(recipientType);
emailLogRequest.setRecipientId(recipientId);
@@ -60,6 +69,7 @@ public class EmailLogDao {
emailLogRequest.setApplicatioId(applicationId);
emailLogRequest.setAmendmentId(amendmentId);
emailLogRequest.setCallId(callId);
emailLogRequest.setUserActionId(userActionId);
return emailLogRequest;
}
}

View File

@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.RecipientTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailConfig;
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
@@ -15,6 +16,7 @@ import net.gepafin.tendermanagement.service.*;
import net.gepafin.tendermanagement.service.impl.EmailService;
import net.gepafin.tendermanagement.service.impl.EmailServiceFactory;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.service.impl.SystemEmailService;
import net.gepafin.tendermanagement.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -137,10 +139,12 @@ public class EmailNotificationDao {
}
}
}
if (rinaldoEmail != null) {
if (GepafinConstant.RINALDO_EMAIL.equals(rinaldoEmail)) {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.PROPERTIES,null ,
rinaldoEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId());
sendMail(applicationEntity.getHubId(), subject, body, List.of(rinaldoEmail), emailLogRequest);
//SMTP
sendMail(null, subject, body, List.of(rinaldoEmail), emailLogRequest);
}
if (applicationEvaluationEntity.isPresent()) {
Long preInstructorId = applicationEvaluationEntity.get().getUserId(); // Assuming UserEntity has an email field
@@ -275,10 +279,16 @@ public class EmailNotificationDao {
public void sendMail(Long hubId, String subject, String body, List<String> recipientEmails, EmailLogRequest emailLogRequest) {
EmailConfig emailConfig = retrieveEmailConfig(hubId);
EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType());
emailService.sendEmail(subject, body, recipientEmails, emailConfig,emailLogRequest);
// emailService.sendEmail(subject, body, recipientEmails, emailConfig);
EmailConfig emailConfig = new EmailConfig();
if (recipientEmails.stream().anyMatch(email -> email.equals(GepafinConstant.RINALDO_EMAIL))) {
emailConfig.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE.getValue());
EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType());
emailService.sendEmail(subject, body, recipientEmails, emailConfig, emailLogRequest);
} else {
emailConfig = retrieveEmailConfig(hubId);
EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType());
emailService.sendEmail(subject, body, recipientEmails, emailConfig, emailLogRequest);
}
}
public EmailConfig retrieveEmailConfig(Long hubId) {

View File

@@ -20,6 +20,7 @@ import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
@@ -68,7 +69,7 @@ public class EvaluationCriteriaDao {
LookUpDataEntity lookupDataEntity = lookUpDataService.getOrCreateLookUpDataEntity(evaluationCriteriaRequest, LookUpDataEntity.LookUpDataTypeEnum.EVALUATION_CRITERIA);
entity.setCall(callEntity);
entity.setLookupData(lookupDataEntity);
entity.setScore(0L);
entity.setScore(BigDecimal.ZERO);
if (evaluationCriteriaRequest.getScore() != null) {
entity.setScore(evaluationCriteriaRequest.getScore());
}

View File

@@ -420,7 +420,8 @@ public class FormDao {
.matchesPattern(value, fieldValidatorBean.getPattern(), fieldLabel) // Only applies if pattern is present
.validateCustom(value, fieldValidatorBean.getCustom(), fieldLabel,contentResponseBean); // Add the custom validation here
if (fieldValidatorBean.getCustom() != null && fieldValidatorBean.getCustom().equals(GepafinConstant.IS_PIVA)) {
String error = validateVatNumber(value, fieldValidatorBean.getCustom(), fieldLabel);
Long hubId = applicationEntity.getHubId();
String error = validateVatNumber(value, fieldLabel,hubId);
if(error != null) {
validator.addError(error);
}
@@ -504,14 +505,14 @@ public class FormDao {
}).filter(value -> !value.isEmpty()).findFirst().orElse(contentResponseBean.getId());
}
public String validateVatNumber(String value,String customRule,String fieldId){
public String validateVatNumber(String value,String fieldId, Long hubId){
String error=null;
if (value!=null && value.matches("^\\d{1,11}$")) {
// Map<String, Object> customData=null;
try {
// Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
vatCheckDao.checkVatNumber(value);
vatCheckDao.checkVatNumber(value, hubId);
// if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
// customData = vatCheckResponse;
// }

View File

@@ -1,10 +1,8 @@
package net.gepafin.tendermanagement.dao;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
@@ -12,7 +10,6 @@ import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.enums.NotificationEnum;
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.model.request.GlobalFilters;
import net.gepafin.tendermanagement.model.request.NotificationReq;
import net.gepafin.tendermanagement.model.request.NotificationRequestBean;
import net.gepafin.tendermanagement.model.response.NotificationResponse;
@@ -28,22 +25,19 @@ 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.opensaml.xmlsec.signature.G;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.isEmpty;
@@ -92,7 +86,7 @@ public class NotificationDao {
log.info("Sending notification to user {} with content: {}", userId, notificationReq.getMessage());
List<Long> companyIds = notificationReq.getCompanyIds();
if (companyIds == null || companyIds.isEmpty()) {
if (companyIds == null || companyIds.isEmpty() || companyIds.stream().allMatch(Objects::isNull)) {
sendToUser(userId, notificationEntity);
} else {
sendToCompanies(userId, companyIds, notificationEntity);
@@ -154,7 +148,7 @@ public class NotificationDao {
notificationEntity.setUserId(notificationReq.getUserId());
notificationEntity.setStatus(NotificationEnum.UNREAD.getValue());
notificationEntity.setIsDeleted(Boolean.FALSE);
notificationEntity.setUserWithCompany(notificationReq.getUserWithCompanyEntity() != null ? notificationReq.getUserWithCompanyEntity() : null);
notificationEntity.setUserWithCompany(notificationReq.getUserWithCompanyEntity());
notificationEntity.setMessage(message);
notificationEntity.setTitle(notificationReq.getTitle());
return notificationEntity;

View File

@@ -62,6 +62,7 @@ public class PdfDao {
public byte[] generatePdf(HttpServletRequest request,Long applicationId) {
try {
log.info("Start generating PDF for applicationId: {}", applicationId);
UserEntity userEntity = validator.validateUser(request);
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
@@ -125,6 +126,7 @@ public class PdfDao {
return pdfBytes;
} catch (Exception e) {
log.error("Error generating PDF for applicationId: {}", applicationId, e);
e.printStackTrace();
}
return null;

View File

@@ -1,20 +1,36 @@
package net.gepafin.tendermanagement.dao;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import feign.FeignException;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.enums.ApplicationSignedDocumentStatusEnum;
import net.gepafin.tendermanagement.enums.ProtocolTypeEnum;
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
import net.gepafin.tendermanagement.repositories.ApplicationSignedDocumentRepository;
import net.gepafin.tendermanagement.service.feignClient.ProtocolService;
import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.ProtocolEntity;
import net.gepafin.tendermanagement.repositories.ProtocolRepository;
import net.gepafin.tendermanagement.util.DateTimeUtil;
@@ -33,6 +49,50 @@ public class ProtocolDao {
@Autowired
private HttpServletRequest request;
@Autowired
private ProtocolService protocolService;
@Value("${codAoo}")
private String codAoo;
@Value("${sviluppumbria.username}")
private String username;
@Value("${password}")
private String password;
@Value("${CLASSIFICA}")
private String classifica;
@Value("${TIPO_PROTOCOLLAZIONE}")
private String TIPO_PROTOCOLLAZIONE;
@Value("${tipoCorrispondenteCompany}")
private String tipoCorrispondenteCompany;
@Value("${tipoCorrispondenteWithoutCompany}")
private String tipoCorrispondenteWithoutCompany;
@Value("${mezzo}")
private String mezzo;
@Value("${indirizzoPec}")
private String indirizzoPec;
@Value("${codiceUo}")
private String codiceUo;
@Value("${competente}")
private Boolean competente;
@Value("${tipoCorrispondente}")
private String tipoCorrispondente;
@Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
public final Logger log = LoggerFactory.getLogger(ProtocolDao.class);
public Long getProtocolNumber(HubEntity hubEntity) {
Long maxProtocolNumber = protocolRepository.findMaxProtocolNumberAndHubId(hubEntity.getId());
@@ -58,11 +118,159 @@ public class ProtocolDao {
}else {
protocolEntity.setType(ProtocolTypeEnum.OUTPUT.getValue());
}
return protocolEntity;
}
public void saveProtocolEntity(ProtocolEntity protocolEntity) {
protocolRepository.save(protocolEntity);
/** This code is responsible for adding a version history log for "create protocol" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(protocolEntity).build());
return protocolEntity;
}
public String getBearerToken(String codAoo, String username, String password) {
log.info("Requesting bearer token for user: {} and codAoo: {}", username, codAoo);
HttpHeaders httpHeaders = Utils.getHeaders();
URI url = URI.create(GepafinConstant.PROTOCOL_SERVICE_BEARER_TOKEN);
try {
ResponseEntity<String> response = protocolService.getBearerToken(httpHeaders, codAoo,username,password);
if (response != null && response.getStatusCode().is2xxSuccessful()) {
log.debug("Bearer token successfully retrieved. HTTP Status: {}", response.getStatusCode());
return response.getBody().toString(); // Use getBody() instead of toString()
} else {
log.warn("Bearer token request failed or returned unexpected status. Response: {}", response);
}
} catch (FeignException ex) {
log.error("FeignException while retrieving bearer token for user {}: {}", username, ex.getMessage(), ex);
Utils.callException(ex.status(), ex);
} catch (Exception ex) {
log.error("Unexpected exception while retrieving bearer token: {}", ex.getMessage(), ex);
}
log.warn("Returning null bearer token for user: {}", username);
return null;
}
public ProtocolEntity createExternalProtocol(ApplicationEntity application, CompanyEntity company, ProtocolEntity protocol) {
log.info("Starting createExternalProtocol for application ID: {}", application.getId());
log.debug("Successfully retrieved bearer token");
ApplicationSignedDocumentEntity applicationSignedDocumentEntity=applicationSignedDocumentRepository.findByApplicationIdAndStatus(application.getId(), ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
String year = String.valueOf(LocalDateTime.now().getYear());
String applicationId = String.valueOf(application.getId());
String mittenteValue="";
String vatNumber ="";
if(company!=null) {
mittenteValue= tipoCorrispondenteCompany;
vatNumber=company.getVatNumber();
}else {
mittenteValue = tipoCorrispondenteWithoutCompany;
vatNumber = company.getCodiceFiscale();
}
String companyName = company.getCompanyName() + " " + vatNumber;
String callName = application.getCall().getName()+" "+ application.getCall().getId();
String callId = GepafinConstant.PROTOCOL_CALL_NAME+ String.valueOf(application.getCall().getId());
String pecEmail=company.getPec();
String docUrl=applicationSignedDocumentEntity.getFilePath()+GepafinConstant.PROTOCOL_DOC_SUFFIX;
Map<String, Object> requestBody = new HashMap<>();
requestBody.put(GepafinConstant.PROTOCOL_DOC_URL,docUrl);
requestBody.put(GepafinConstant.PROTOCOL_COMPANY_NAME,companyName);
requestBody.put(GepafinConstant.PROTOCOL_DOC_HASH,applicationSignedDocumentEntity.getFileHash());
requestBody.put(GepafinConstant.PROTOCOL_TIPO_PROTOCOLLAZIONE,TIPO_PROTOCOLLAZIONE);
Map<String, Object> mittente = new HashMap<>();
mittente.put(GepafinConstant.PROTOCOL_TIPO_CORRISPONDENTE_COMPANY, mittenteValue);
mittente.put(GepafinConstant.PROTOCOL_COMPANY_NAME_VAT_NUMBER,company.getCompanyName());
mittente.put(GepafinConstant.PROTOCOL_MEZZO,mezzo);
mittente.put(GepafinConstant.PROTOCOL_INDIRIZZO_PEC,pecEmail);
mittente.put(GepafinConstant.PROTOCOL_COMPANY_VAT_NUMBER,vatNumber);
List<Map<String,Object>> destinatariObject=new ArrayList<>();
Map<String, Object> destinatari = new HashMap<>();
destinatari.put(GepafinConstant.PROTOCOL_CODICE_UO,codiceUo);
destinatari.put(GepafinConstant.PROTOCOL_COMPETENTE,competente);
destinatari.put(GepafinConstant.PROTOCOL_TIPO_CORRISPONDENTE,tipoCorrispondente);
requestBody.put(GepafinConstant.PROTOCOL_MITTENTE,mittente);
destinatariObject.add(destinatari);
requestBody.put(GepafinConstant.PROTOCOL_DESTINATARI,destinatariObject);
List<Map<String,Object>> listObject=new ArrayList<>();
listObject.add(requestBody);
log.info("Preparing to create protocol with data: year={}, applicationId={}, companyName={}, callName={}, callId={}",
year, applicationId, companyName, callName, callId);
ResponseEntity<Object> response=null;
try {
String bearerToken = getBearerToken(codAoo, username, password);
if (bearerToken == null) {
log.error("Bearer token retrieval failed for user: {}", username);
return protocol;
}
HttpHeaders httpHeaders = Utils.getHeaders();
httpHeaders.set(GepafinConstant.AUTHORIZATION, "Bearer " + bearerToken);
URI url = URI.create(GepafinConstant.PROTOCOL_SERVICE_CREATE_PROTOCOL);
response = protocolService.createProtocol(httpHeaders, classifica, year, applicationId, companyName, callName, callId,listObject
);
log.info("Protocol creation response: status={}, body={}", response.getStatusCode(), response.getBody());
} catch (FeignException ex) {
log.error("FeignException during protocol creation for application ID {}: {}", applicationId, ex.getMessage(), ex);
// Utils.callException(ex.status(), ex);
} catch (Exception ex) {
log.error("Unexpected exception during protocol creation for application ID {}: {}", applicationId, ex.getMessage(), ex);
}
log.info("Finished createExternalProtocol for application ID: {}", application.getId());
if(response!=null && response.getBody()!=null) {
protocol = extractDetailForProtocol((List<Map<String, Object>>) response.getBody(), protocol);
}
return protocol;
}
public ProtocolEntity extractDetailForProtocol(List<Map<String,Object>> responseObject, ProtocolEntity protocol) {
Map<String,Object> responseField= responseObject.get(0);
Object yearObj = responseField.get(GepafinConstant.PROTOCOL_EXTERNAL_YEAR);
Integer externalProtocolYear = null;
if (yearObj instanceof Integer) {
externalProtocolYear = (Integer) yearObj;
} else if (yearObj instanceof String) {
try {
externalProtocolYear = Integer.parseInt((String) yearObj);
} catch (NumberFormatException e) {
// handle invalid format gracefully
externalProtocolYear = null;
}
}
Object dateObj = responseField.get(GepafinConstant.PROTOCOL_EXTERNAL_DATE);
LocalDateTime externalProtocolDate = null;
if (dateObj instanceof LocalDateTime) {
externalProtocolDate = (LocalDateTime) dateObj;
} else if (dateObj instanceof String) {
externalProtocolDate = DateTimeUtil.parseStringToLocalDateTime((String) dateObj);
}
if(externalProtocolDate!=null){
protocol.setExternalProtocolDate(externalProtocolDate);
}
if (externalProtocolYear!=null){
protocol.setExternalProtocolYear(externalProtocolYear);
}
String externalProtocolNumber = (String) responseField.get(GepafinConstant.PROTOCOL_EXTERNAL_NUMBER);
if (Boolean.FALSE.equals(StringUtils.isEmpty(externalProtocolNumber))) {
protocol.setExternalProtocolNumber(externalProtocolNumber);
}
protocolRepository.save(protocol);
return protocol;
}
}

View File

@@ -15,6 +15,7 @@ import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.model.util.SortBy;
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.service.RoleService;
@@ -42,6 +43,7 @@ import org.springframework.stereotype.Component;
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;
@@ -109,9 +111,15 @@ public class UserDao {
@Autowired
private EmailNotificationDao emailNotificationDao;
@Autowired
private EmailLogRepository emailLogRepository;
@Value("${fe.base.url}")
private String feBaseUrl;
@Autowired
EmailDao emailDao;
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
if (StringUtils.isEmpty(userReq.getHubUuid())) {
@@ -134,7 +142,6 @@ public class UserDao {
authenticationService.createSuccessLoginAttempt(loginAttemptEntity);
}
JWTToken token = authService.getJWTTokenBean(userEntity, Boolean.TRUE, loginAttemptEntity.getId());
/** This code is responsible for adding a version history log for the "Create beneficiary" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).newData(beneficiary).build());
@@ -142,12 +149,40 @@ public class UserDao {
/** This code is responsible for adding a version history log for the "Create user" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).newData(userEntity).build());
List<EmailSendResponse> responses = new ArrayList<>();
if(Boolean.FALSE.equals(roleEntity.getRoleType().equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue()))){
sendEmailToOnboardingUser(userEntity, userReq );
boolean isEmailSendSuccess = isEmailSentSuccessfully(userEntity.getId());
EmailSendResponse emailSendResponse = new EmailSendResponse();
if (Boolean.FALSE.equals(isEmailSendSuccess)){
emailSendResponse.setIsEmailSend(false);
Long userActionId =(Long)request.getAttribute(GepafinConstant.USER_ACTION_ID);
emailSendResponse.setUserActionId(userActionId);
emailSendResponse.setEmailScenario(EmailScenarioTypeEnum.USER_CREATION);
saveEmailSendResponseToUser(emailSendResponse,userEntity);
responses = List.of(emailSendResponse);
}
else{
responses = Collections.emptyList();
}
}
JWTToken token = authService.getJWTTokenBean(userEntity, Boolean.TRUE, loginAttemptEntity.getId(),responses);
return token;
}
public void sendEmailToOnboardingUser(UserEntity userEntity,UserReq userReq){
public boolean isEmailSentSuccessfully(Long userId) {
Optional<EmailLogEntity> latestLogOpt = emailLogRepository
.findTopByUserIdAndEmailTypeAndIsDeletedFalseOrderByCreatedDateDesc(userId, EmailScenarioTypeEnum.USER_CREATION.getValue());
return latestLogOpt
.map(log -> StatusTypeEnum.SUCCESS.getValue().equals(log.getSendStatus()))
.orElse(false);
}
public void sendEmailToOnboardingUser(UserEntity userEntity,UserReq userReq){
SystemEmailTemplateResponse emailTemplate;
RoleStatusEnum roleStatus = RoleStatusEnum.valueOf(userEntity.getRoleEntity().getRoleType());
@@ -382,6 +417,7 @@ public class UserDao {
RoleResponseBean roleResponseBean = roleDao.convertRoleEntityToRoleResponse(userEntity.getRoleEntity());
userResponseBean.setRole(roleResponseBean);
userResponseBean.setLastLogin(userEntity.getLastLogin());
userResponseBean.setEmailSendResponse(userEntity.getEmailSendResponse());
List<CompanyResponse> companyResponseBeans = companyDao.getCompanyByUserId(userEntity.getId());
userResponseBean.setCompanies(companyResponseBeans);
if (userEntity.getBeneficiary() == null) {
@@ -459,7 +495,7 @@ public class UserDao {
return user;
}
public void initiatePasswordReset(InitiatePasswordResetReq resetReq) {
public InitiatePasswordResetResponse initiatePasswordReset(InitiatePasswordResetReq resetReq) {
UserEntity user = userRepository.findUserExcludingRoleType(
resetReq.getEmail(),
resetReq.getHubUuid(),
@@ -478,9 +514,28 @@ public class UserDao {
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldUserEntity).newData(user).build());
log.info("Password reset token generated for user: {}", resetReq.getEmail());
sendResetPasswordTokenEmail(user, token);
InitiatePasswordResetResponse initiatePasswordResetResponse = new InitiatePasswordResetResponse();
EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
List<EmailSendResponse> responses = List.of(emailSendResponse);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
initiatePasswordResetResponse.setEmailSendResponse(responses);
saveEmailSendResponseToUser(emailSendResponse,user);
}
else{
initiatePasswordResetResponse.setEmailSendResponse(Collections.emptyList());
}
return initiatePasswordResetResponse;
}
private void saveEmailSendResponseToUser(EmailSendResponse newResponse, UserEntity user) {
List<EmailSendResponse> mergedResponses = Utils.mergeEmailSendResponses(
user.getEmailSendResponse(), newResponse
);
user.setEmailSendResponse(mergedResponses);
userRepository.save(user);
}
public void sendResetPasswordTokenEmail(UserEntity user, String token) {
SystemEmailTemplateResponse emailTemplate = systemEmailTemplatesService.retrieveTemplateByTypeAndCall(

View File

@@ -3,12 +3,17 @@ package net.gepafin.tendermanagement.dao;
import feign.FeignException;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.VatCheckVersionTypeEnum;
import net.gepafin.tendermanagement.model.response.VatCheckResponseBean;
import net.gepafin.tendermanagement.repositories.CompanyRepository;
import net.gepafin.tendermanagement.repositories.GlobalConfigRepository;
import net.gepafin.tendermanagement.service.feignClient.VatCheckV1Service;
import net.gepafin.tendermanagement.service.feignClient.VatCheckV2Service;
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.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -48,6 +53,9 @@ public class VatCheckDao {
@Autowired
private GlobalConfigRepository globalConfigRepository;
@Autowired
private CompanyRepository companyRepository;
public final Logger log = LoggerFactory.getLogger(VatCheckDao.class);
public VatCheckResponseBean checkVatNumberV1(String vatNumber) {
@@ -56,6 +64,7 @@ public class VatCheckDao {
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
if (Boolean.TRUE.equals(Boolean.parseBoolean(isVatCheckGloballyDisabled))) {
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
vatCheckResponseBean.setVersion(VatCheckVersionTypeEnum.V1);
return vatCheckResponseBean;
}
try {
@@ -96,6 +105,7 @@ public class VatCheckDao {
public static void processValidResponseV1(Map<String, Object> responseMap, VatCheckResponseBean vatCheckResponseBean) {
Object dataObj = responseMap.get("data");
vatCheckResponseBean.setVersion(VatCheckVersionTypeEnum.V1);
if (dataObj instanceof Map<?, ?> rawDataMap) {
Map<String, Object> responseBody = new LinkedHashMap<>();
rawDataMap.forEach((k, v) -> {
@@ -118,9 +128,20 @@ public class VatCheckDao {
}
public VatCheckResponseBean checkVatNumber(String vatNumber) {
public VatCheckResponseBean checkVatNumber(String vatNumber, Long hubId) {
try {
CompanyEntity company = companyRepository.findByVatNumberAndHubId(vatNumber, hubId);
if (company != null && Boolean.FALSE.equals(StringUtils.isEmpty(company.getJson()))) {
Map<String, Object> responseMap = Utils.convertJsonStringToMap(company.getJson());
VatCheckResponseBean jsonResponse = validateJsonFromDb(responseMap);
if (jsonResponse != null) {
return jsonResponse;
}
}
String vatApiVersion = getVatCheckVersion();
if(!isVatCheckApiV2(vatApiVersion)){
return checkVatNumberV1(vatNumber);
@@ -134,6 +155,26 @@ public class VatCheckDao {
return vatCheckResponseBean;
}
}
private VatCheckResponseBean validateJsonFromDb(Map<String, Object> responseMap) {
if (responseMap == null || !responseMap.containsKey("data")) return null;
Object data = responseMap.get("data");
if (data instanceof Map<?, ?> dataMap && !dataMap.isEmpty()) {
VatCheckResponseBean response = new VatCheckResponseBean();
processValidResponseV1(responseMap, response);
return response;
}
if (data instanceof List<?> dataList && !dataList.isEmpty()) {
VatCheckResponseBean response = new VatCheckResponseBean();
processValidResponse(responseMap, response);
return response;
}
return null;
}
public VatCheckResponseBean checkVatNumberV2(String vatNumber) {
@@ -142,6 +183,7 @@ public class VatCheckDao {
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
if (Boolean.TRUE.equals(Boolean.parseBoolean(isVatCheckGloballyDisabled))) {
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
vatCheckResponseBean.setVersion(VatCheckVersionTypeEnum.V2);
return vatCheckResponseBean;
}
try {
@@ -175,6 +217,7 @@ public class VatCheckDao {
public static void processValidResponse(Map<String, Object> responseMap, VatCheckResponseBean vatCheckResponseBean) {
vatCheckResponseBean.setVersion(VatCheckVersionTypeEnum.V2);
if (responseMap == null || !responseMap.containsKey("data")) {
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
return;

View File

@@ -3,8 +3,10 @@ package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Data;
import org.hibernate.annotations.Where;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name="application_amendment_request")
@@ -53,7 +55,10 @@ public class ApplicationAmendmentRequestEntity extends BaseEntity {
@Column(name = "amendment_document")
private String amendmentDocument;
@Column(name = "CLOSING_DATE")
private LocalDateTime closingDate;
@Convert(converter = EmailSendResponseConverter.class)
@Column(name = "EMAIL_SEND_RESPONSE", columnDefinition = "TEXT")
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -3,9 +3,12 @@ package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import net.gepafin.tendermanagement.model.BaseBean;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import org.hibernate.annotations.Immutable;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Immutable
@@ -13,12 +16,12 @@ import java.time.LocalDateTime;
@Getter
@Setter
@IdClass(ApplicationAmendmentRequestViewId.class)
public class ApplicationAmendmentRequestView {
public class ApplicationAmendmentRequestView extends BaseEntity {
@Id
@Column(name = "ID")
private Long id;
// @Id
// @Column(name = "ID")
// private Long id;
@Column(name = "APPLICATION_ID")
private Long applicationId;
@@ -56,12 +59,17 @@ public class ApplicationAmendmentRequestView {
@Column(name = "APPLICATION_USER_ID")
private Long applicationUserId;
@Column(name = "CREATED_DATE")
private String createdDate;
@Column(name = "UPDATED_DATE")
private String updatedDate;
// @Column(name = "CREATED_DATE")
// private String createdDate;
//
// @Column(name = "UPDATED_DATE")
// private String updatedDate;
@Column(name = "IS_DELETED")
private Boolean isDeleted;
@Convert(converter = EmailSendResponseConverter.class)
@Column(name = "EMAIL_SEND_RESPONSE", columnDefinition = "TEXT")
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -3,8 +3,10 @@ package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Data;
import org.hibernate.annotations.Where;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Entity
@@ -70,4 +72,7 @@ public class ApplicationEvaluationEntity extends BaseEntity{
@Column(name = "evaluationVersion")
private String evaluationVersion;
@Convert(converter = EmailSendResponseConverter.class)
@Column(name = "EMAIL_SEND_RESPONSE", columnDefinition = "TEXT")
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -0,0 +1,118 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Immutable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
@Entity
@Immutable
@Table(name = "application_form_view")
@Getter
@Setter
@IdClass(ApplicationFormViewId.class)
public class ApplicationFormView {
@Id
@Column(name = "id")
private Long id;
@Column(name = "application_id")
private Long applicationId;
@Column(name = "call_id")
private Long callId;
@Column(name = "form_id")
private Long formId;
@Column(name = "application_form_id")
private Long applicationFormId;
@Column(name = "field_id")
private String fieldId;
@Column(name = "field_label")
private String fieldLabel;
@Column(name = "field_type")
private String fieldType;
@Column(name = "field_value")
private String fieldValue;
@Column(name = "report_enable")
private Boolean reportEnable;
@Column(name = "report_header")
private String reportHeader;
@Column(name = "status")
private String status;
@Column(name = "amount_requested")
private BigDecimal amountRequested;
@Column(name = "amount_accepted")
private BigDecimal amountAccepted;
@Column(name = "is_deleted")
private boolean isDeleted;
@Column(name = "hub_id")
private Long hubId;
@Column(name = "user_id")
private Long userId;
@Column(name = "evaluation_version")
private String evaluationVersion;
@Column(name = "company_id")
private Long companyId;
@Column(name = "company_name")
private String companyName;
@Column(name = "company_vat_number")
private String companyVatNumber;
@Column(name = "codice_ateco")
private String codiceAteco;
@Column(name = "company_codice_fiscale")
private String companyCodiceFiscale;
@Column(name = "protocol_number")
private Long protocolNumber;
@Column(name = "user_codice_fiscale")
private String userCodiceFiscale;
@Column(name = "user_name")
private String userName;
@Column(name = "legal_representative")
private Boolean legalRepresentative;
@Column(name = "call_title")
private String callTitle;
@Column(name = "call_end_date")
private LocalDate callEndDate;
@Column(name = "call_end_time")
private LocalTime callEndTime;
@Column(name = "call_start_date")
private LocalDate callStartDate;
@Column(name = "call_start_time")
private LocalTime callStartTime;
}

View File

@@ -0,0 +1,20 @@
package net.gepafin.tendermanagement.entities;
import lombok.Data;
import java.io.Serializable;
import java.util.Objects;
@Data
public class ApplicationFormViewId implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
public ApplicationFormViewId() {
}
public ApplicationFormViewId(Long id) {
this.id = id;
}
}

View File

@@ -27,4 +27,6 @@ public class ApplicationSignedDocumentEntity extends BaseEntity {
@Column(name="STATUS")
private String status;
@Column(name="FILE_HASH")
private String fileHash;
}

View File

@@ -0,0 +1,70 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Data;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import org.hibernate.annotations.Immutable;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Immutable
@Data
@Table(name = "assigned_applications_view")
@IdClass(AssignedApplicationsViewId.class)
public class AssignedApplicationsView{
@Id
@Column(name = "ID")
private Long id;
@Column(name = "APPLICATION_ID")
private Long applicationId;
@Column(name = "USER_ID")
private Long userId;
@Column(name = "PROTOCOL_NUMBER")
private Long protocolNumber;
@Column(name = "CALL_NAME")
private String callName;
@Column(name = "COMPANY_NAME")
private String companyName;
@Column(name = "STATUS")
private String status;
@Column(name = "NDG")
private String ndg;
@Column(name = "APPOINTMENT_ID")
private String appointmentId;
@Column(name = "APPLICATION_STATUS")
private String applicationStatus;
@Column(name = "SUBMISSION_DATE")
private LocalDateTime submissionDate;
@Column(name = "EVALUATION_END_DATE")
private LocalDateTime evaluationEndDate;
@Column(name = "CREATED_DATE")
private LocalDateTime createdDate;
@Column(name = "UPDATED_DATE")
private LocalDateTime updatedDate;
@Column(name = "IS_DELETED")
private Boolean isDeleted;
@Convert(converter = EmailSendResponseConverter.class)
@Column(name = "EMAIL_SEND_RESPONSE", columnDefinition = "TEXT")
private List<EmailSendResponse> emailSendResponse;
@Column(name = "HUB_ID")
private Long hubId;
}

View File

@@ -0,0 +1,17 @@
package net.gepafin.tendermanagement.entities;
import lombok.Data;
import java.io.Serializable;
@Data
public class AssignedApplicationsViewId implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
public AssignedApplicationsViewId() {}
public AssignedApplicationsViewId(Long id) {
this.id = id;
}
}

View File

@@ -53,9 +53,6 @@ public class CompanyEntity extends BaseEntity{
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
// @Column(name = "JSON")
// private String json;
@Column(name = "NDG")
private String ndg;
@@ -64,4 +61,7 @@ public class CompanyEntity extends BaseEntity{
@Column(name = "JSON")
private String json;
@Column(name = "PEC")
private String pec;
}

View File

@@ -55,5 +55,9 @@ public class EmailLogEntity extends BaseEntity{
@Column(name = "call_id")
private Long callId;
@ManyToOne
@JoinColumn(name = "user_action_id")
private UserActionEntity userAction;
}

View File

@@ -0,0 +1,43 @@
package net.gepafin.tendermanagement.entities;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import java.io.IOException;
import java.util.List;
@Converter
public class EmailSendResponseConverter implements AttributeConverter<List<EmailSendResponse>, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(List<EmailSendResponse> attribute) {
try {
if (attribute == null) {
attribute = List.of();
}
return objectMapper.writeValueAsString(attribute);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Error converting list to JSON", e);
}
}
@Override
public List<EmailSendResponse> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.isBlank()) {
return List.of(); // or null if you prefer
}
try {
return objectMapper.readValue(dbData, new TypeReference<List<EmailSendResponse>>() {});
} catch (IOException e) {
throw new IllegalArgumentException("Error reading JSON from database", e);
}
}
}

View File

@@ -7,6 +7,9 @@ import jakarta.persistence.Table;
import lombok.Data;
import org.hibernate.annotations.Where;
import java.math.BigDecimal;
@Entity
@Table(name = "EVALUATION_CRITERIA")
@Data
@@ -22,6 +25,6 @@ public class EvaluationCriteriaEntity extends BaseEntity {
private LookUpDataEntity lookupData;
@Column(name = "SCORE", nullable = false)
private Long score;
private BigDecimal score;
}

View File

@@ -5,6 +5,7 @@ import lombok.Data;
import net.gepafin.tendermanagement.config.LocalTimeAttributeConverter;
import org.hibernate.annotations.Where;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Entity
@@ -35,4 +36,14 @@ public class ProtocolEntity extends BaseEntity {
@Column(name = "type")
private String type;
@Column(name = "external_protocol_year")
private Integer externalProtocolYear;
@Column(name = "external_protocol_date")
private LocalDateTime externalProtocolDate;
@Column(name = "external_protocol_number")
private String externalProtocolNumber;
}

View File

@@ -54,7 +54,8 @@ public class SystemEmailTemplatesEntity extends BaseEntity {
USER_ONBOARDING_CONFIDI("USER_ONBOARDING_CONFIDI"),
USER_ONBOARDING_BANDI("USER_ONBOARDING_BANDI"),
PASSWORD_RESET("PASSWORD_RESET"),
INADMISSIBILITY_TEMPLATE("INADMISSIBILITY_NOTIFICATION");
INADMISSIBILITY_TEMPLATE("INADMISSIBILITY_NOTIFICATION"),
APPLICATION_SUBMISSION_FAILURE_NOTIFICATION("APPLICATION_SUBMISSION_FAILURE_NOTIFICATION");
private String value;
SystemEmailTemplatesEntityTypeEnum(String value) {

View File

@@ -8,8 +8,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "GEPAFIN_USER")
@@ -71,4 +73,9 @@ public class UserEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
@Convert(converter = EmailSendResponseConverter.class)
@Column(name = "EMAIL_SEND_RESPONSE", columnDefinition = "TEXT")
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -11,7 +11,8 @@ public enum EmailScenarioTypeEnum {
APPLICATION_ADMISSIBLE("APPLICATION_ADMISSIBLE"),
USER_CREATION("USER_CREATION"),
PASSWORD_RESET_REQUEST("PASSWORD_RESET_REQUEST"),
APPLICATION_REJECTED("APPLICATION_REJECTED");
APPLICATION_REJECTED("APPLICATION_REJECTED"),
APPLICATION_SUBMISSION_FAILURE("APPLICATION_SUBMISSION_FAILURE");
private final String value;

View File

@@ -5,7 +5,8 @@ import com.fasterxml.jackson.annotation.JsonValue;
public enum EmailServiceTypeEnum {
MAILGUN_SERVICE("MAILGUN_SERVICE"),
PEC_SERVICE("PEC_SERVICE");
PEC_SERVICE("PEC_SERVICE"),
SYSTEM_EMAIL_SERVICE("SYSTEM_EMAIL_SERVICE");
private String value;

View File

@@ -14,7 +14,8 @@ public enum NotificationTypeEnum {
EVALUATION_EXPIRED("EVALUATION_EXPIRED"),
AMENDMENT_EXPIRATION_REMINDER("AMENDMENT_EXPIRATION_REMINDER"),
EVALUATION_EXPIRATION_REMINDER("EVALUATION_EXPIRATION_REMINDER"),
COMPANY_DOCUMENT_EXPIRATION_REMINDER("COMPANY_DOCUMENT_EXPIRATION_REMINDER");
COMPANY_DOCUMENT_EXPIRATION_REMINDER("COMPANY_DOCUMENT_EXPIRATION_REMINDER"),
PEC_EMAIL_SENDING_FAILURE("PEC_EMAIL_SENDING_FAILURE");
private final String value;

View File

@@ -46,6 +46,7 @@ public enum UserActionContextEnum {
GET_SIGNED_DOCUMENT("GET_SIGNED_DOCUMENT"),
GET_NEXT_PREVIOUS_FORM("GET_NEXT_PREVIOUS_FORM"),
DOWNLOAD_APPLICATION_DOC_ZIP("DOWNLOAD_APPLICATION_DOC_ZIP"),
READMIT_APPLICATION("READMIT_APPLICATION"),
/** FAQ action context **/
CREATE_FAQ("CREATE_FAQ"),
@@ -215,7 +216,9 @@ public enum UserActionContextEnum {
GET_ALL_USER_ACTION_BY_PAGINATION("GET_ALL_USER_ACTION_BY_PAGINATION"),
GET_ALL_USER_BY_PAGINATION("GET_ALL_USER_BY_PAGINATION"),
UPDATE_CALL_END_DATE_AND_TIME("UPDATE_CALL_END_DATE_AND_TIME"),
UPDATE_EXPIRED_CALL("UPDATE_EXPIRED_CALL") ;
UPDATE_EXPIRED_CALL("UPDATE_EXPIRED_CALL"),
RESEND_EMAIL("RESEND_EMAIL"),
SEND_REMINDER_EMAIL("SEND_REMINDER_EMAIL");
private final String value;

View File

@@ -12,7 +12,8 @@ public enum UserActionLogsEnum {
DOWNLOAD("DOWNLOAD"),
UPLOAD("UPLOAD"),
SCHEDULER("SCHEDULER"),
SCRIPT("SCRIPT");
SCRIPT("SCRIPT"),
EMAIL("EMAIL");
private final String value;

View File

@@ -14,6 +14,4 @@ public class CallPageableRequestBean {
private List<CallStatusEnum> status;
private Map<String, FilterCriteria> filters;
private Boolean confidi;
}

View File

@@ -2,9 +2,11 @@ package net.gepafin.tendermanagement.model.request;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class CriteriaRequest {
private Long id;
private Long score;
private BigDecimal score;
private Boolean valid;
}

View File

@@ -37,4 +37,6 @@ public class EmailLogRequest {
private Long callId;
private Long userActionId;
}

View File

@@ -3,9 +3,11 @@ package net.gepafin.tendermanagement.model.request;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@NoArgsConstructor
@Data
public class EvaluationCriteriaReq extends LookUpDataReq{
private Long score;
private BigDecimal score;
}

View File

@@ -3,11 +3,13 @@ package net.gepafin.tendermanagement.model.request;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@NoArgsConstructor
@Data
public class EvaluationCriteriaRequest extends LookUpDataReq {
private Long callId;
private Long score;
private BigDecimal score;
}

View File

@@ -32,4 +32,5 @@ public class ApplicationAmendmentRequestResponse {
private String internalNote;
private ApplicationAmendmentRequestEnum status;
private String emailTemplate;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -0,0 +1,36 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.enums.ApplicationAmendmentRequestEnum;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class ApplicationAmendmentRequestResponseBean {
private Long id;
private String callEmail;
private String note;
private Long responseDays;
private LocalDateTime startDate;
private Boolean isSendNotification;
private Boolean isSendEmail;
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;
private LocalDateTime expirationDate;
private List<CommunicationResponseBean> commentsList;
private String internalNote;
private ApplicationAmendmentRequestEnum status;
private String emailTemplate;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -3,6 +3,7 @@ package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class ApplicationAmendmentRequestViewResponse {
@@ -24,4 +25,6 @@ public class ApplicationAmendmentRequestViewResponse {
private String assigendUserName;
private String status;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -48,5 +48,6 @@ public class ApplicationEvaluationFormResponse {
private Long appointmentTemplateId;
private String companyVatNumber;
private String companyCodiceAteco;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -49,5 +49,6 @@ public class ApplicationEvaluationResponse {
private EvaluationVersionEnum evaluationVersion;
private String companyVatNumber;
private String companyCodiceAteco;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -0,0 +1,52 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.enums.ApplicationEvaluationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.EvaluationVersionEnum;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class ApplicationEvaluationResponseBean {
private Long id;
private Long applicationId;
private ApplicationStatusTypeEnum applicationStatus;
private Long assignedApplicationId;
private String note;
private ApplicationEvaluationStatusTypeEnum status;
private Long minScore;
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;
private BigDecimal amountRequested;
private BigDecimal amountAccepted;
private LocalDateTime dateAccepted;
private LocalDateTime dateRejected;
private Long numberOfCheck;
private Long appointmentTemplateId;
private EvaluationVersionEnum evaluationVersion;
private String companyVatNumber;
private String companyCodiceAteco;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -11,4 +11,5 @@ public class ApplicationSignedDocumentResponse extends BaseBean{
private String fileName;
private String filePath;
private ApplicationSignedDocumentStatusEnum status;
private String fileHash;
}

View File

@@ -0,0 +1,27 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.model.BaseBean;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class AssignedApplicationViewResponse extends BaseBean {
private Long userId;
private Long applicationId;
private AssignedApplicationEnum status;
private LocalDateTime submissionDate;
private ApplicationStatusTypeEnum applicationStatus;
private LocalDateTime evaluationEndDate;
private String ndg;
private String appointmentId;
private Long protocolNumber;
private String callName;
private String companyName;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -2,14 +2,15 @@ package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
public class CriteriaResponse {
private Long id;
private String label;
private Long score;
private Long maxScore;
private BigDecimal score;
private BigDecimal maxScore;
private List<CriteriaMappedField> criteriaMappedFields;
private Boolean valid;
}

View File

@@ -0,0 +1,18 @@
package net.gepafin.tendermanagement.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmailReminderResponse {
@JsonProperty("emailSendResponse")
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -0,0 +1,12 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class EmailResendResponseBean {
private EmailSendResponse emailSendResponse;
}

View File

@@ -0,0 +1,11 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum;
@Data
public class EmailSendResponse {
private Boolean isEmailSend;
private Long userActionId;
private EmailScenarioTypeEnum emailScenario;
}

View File

@@ -3,9 +3,11 @@ package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.model.BaseBean;
import java.math.BigDecimal;
@Data
public class EvaluationCriteriaResponseBean extends LookUpDataResponse{
private Long score;
private BigDecimal score;
}

View File

@@ -0,0 +1,15 @@
package net.gepafin.tendermanagement.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class InitiatePasswordResetResponse {
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -48,4 +48,5 @@ public class UserResponseBean extends BaseBean {
private Boolean thirdParty;
private String emailPec;
private List<EmailSendResponse> emailSendResponse;
}

View File

@@ -1,6 +1,8 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Getter;
import lombok.Setter;
import net.gepafin.tendermanagement.enums.VatCheckVersionTypeEnum;
import java.util.Map;
@Getter
@@ -9,4 +11,5 @@ public class VatCheckResponseBean {
private Boolean valid;
private Map<String, Object> vatCheckResponse;
private String message;
private VatCheckVersionTypeEnum version;
}

View File

@@ -3,8 +3,11 @@ package net.gepafin.tendermanagement.model.util;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import net.gepafin.tendermanagement.model.response.LoginResponse;
import java.util.List;
/**
* JWTToken
*/
@@ -15,10 +18,20 @@ public class JWTToken {
@JsonProperty("user")
private LoginResponse loginResponse;
@JsonProperty("emailSendResponse")
private List<EmailSendResponse> emailSendResponse;
public JWTToken(String token, LoginResponse loginResponse) {
this.token = token;
this.loginResponse = loginResponse;
}
public JWTToken(String token, LoginResponse loginResponse, List<EmailSendResponse> emailSendResponse) {
this.token = token;
this.loginResponse = loginResponse;
this.emailSendResponse = emailSendResponse;
}
}

View File

@@ -150,4 +150,8 @@ public interface ApplicationAmendmentRequestRepository extends JpaRepository<App
@Query("SELECT COUNT(a) FROM ApplicationAmendmentRequestEntity a WHERE a.applicationId IN :applicationIds AND a.status IN :statuses AND a.isDeleted = false")
Long countAmendmentsByApplicationIds(@Param("applicationIds") List<Long> applicationIds, @Param("statuses") List<String> statuses);
ApplicationAmendmentRequestEntity findByIdAndIsDeletedFalseAndStatus(Long id,String status);
ApplicationAmendmentRequestEntity findByIdAndIsDeletedFalseAndStatusIn(Long id, List<String> statusList);
}

View File

@@ -76,5 +76,14 @@ public interface ApplicationEvaluationRepository extends JpaRepository<Applicati
@Param("assignedApplicationId") Long assignedApplicationId
);
Optional<ApplicationEvaluationEntity> findByAssignedApplicationsEntity_IdAndStatusAndIsDeletedFalse(
Long assignedApplicationId,
String status
);
@Query("SELECT ae FROM ApplicationEvaluationEntity ae WHERE ae.applicationId = :applicationId AND ae.isDeleted = false")
ApplicationEvaluationEntity findByApplicationId(@Param("applicationId") Long applicationId);
}

View File

@@ -0,0 +1,17 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.ApplicationFormView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ApplicationFormViewRepository extends JpaRepository<ApplicationFormView,Long>, JpaSpecificationExecutor<ApplicationFormView> {
@Query("SELECT v FROM ApplicationFormView v WHERE v.callId = :callId AND v.reportEnable = true")
List<ApplicationFormView> findByCallId(Long callId);
}

View File

@@ -178,4 +178,7 @@ public interface ApplicationRepository extends JpaRepository<ApplicationEntity,
void resetNdgStatusForInProgress(@Param("status") String status);
boolean existsByCallId(Long callId);
ApplicationEntity findByIdAndStatusAndIsDeletedFalse( Long id, String status);
}

View File

@@ -3,6 +3,8 @@ package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.ApplicationView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface ApplicationViewRepository extends JpaRepository<ApplicationView,Long> , JpaSpecificationExecutor<ApplicationView> {
}

View File

@@ -110,4 +110,8 @@ public interface AssignedApplicationsRepository extends JpaRepository<AssignedAp
@Param("sevenDaysAgo") LocalDateTime sevenDaysAgo);
Optional<AssignedApplicationsEntity> findByApplicationIdAndStatusAndIsDeletedFalse( Long applicationId, String status);
}

View File

@@ -0,0 +1,9 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.AssignedApplicationsView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface AssignedApplicationsViewRepository extends JpaRepository<AssignedApplicationsView,Long> , JpaSpecificationExecutor<AssignedApplicationsView> {
}

View File

@@ -1,11 +1,28 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface EmailLogRepository extends JpaRepository<EmailLogEntity,Long> {
List<EmailLogEntity> findByUserIdAndAmendmentIdAndIsDeletedFalse(Long userId,Long amendmentId);
List<EmailLogEntity> findByUserActionId(Long userActionId);
List<EmailLogEntity> findByUserActionIdAndEmailServiceTypeAndSendStatus(
Long userActionId, String emailServiceType, String sendStatus);
Optional<EmailLogEntity> findTopByUserIdAndEmailTypeAndIsDeletedFalseOrderByCreatedDateDesc(Long userId, String emailType);
List<EmailLogEntity> findByUserActionIdAndEmailServiceType(
Long userActionId, String emailServiceType);
EmailLogEntity findTopByUserActionIdAndEmailServiceTypeAndSendStatusOrderByIdDesc(
Long userActionId,
String emailServiceType,
String sendStatus
);
}

View File

@@ -122,7 +122,7 @@ public class ApplicationAmendmentScheduler {
.findEvaluationsWithoutActiveAmendmentsByIds(applicationEvaluationIds);
evaluationsWithoutActiveAmendmentList.forEach(evaluation -> {
try {
applicationAmendmentRequestDao.calculateEndDateAndSuspensionDays(evaluation);
applicationAmendmentRequestDao.calculateEndDateAndSuspensionDaysOnExpirationOrClosing(evaluation);
updateEvaluationStatus(evaluation);

View File

@@ -24,6 +24,7 @@ import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -87,7 +88,10 @@ public class ApplicationEvaluationScheduler {
evaluation.setStatus(ApplicationEvaluationStatusTypeEnum.EXPIRED.getValue());
evaluation = applicationEvaluationRepository.save(evaluation);
Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_EXPIRED);
// Map<String, String> placeHolders = notificationDao.sendNotificationToBeneficiary(application, NotificationTypeEnum.EVALUATION_EXPIRED);
Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("{{call_name}}", application.getCall().getName());
placeHolders.put("{{protocol_number}}", String.valueOf(application.getProtocol().getProtocolNumber()));
notificationDao.sendNotificationToSuperUser(application,placeHolders,NotificationTypeEnum.EVALUATION_EXPIRED);
notificationDao.sendNotificationToInstructor(placeHolders,evaluation,NotificationTypeEnum.EVALUATION_EXPIRED);
notificationDao.sendNotificationToInstructorManager(placeHolders,evaluation,NotificationTypeEnum.EVALUATION_EXPIRED);

View File

@@ -21,4 +21,5 @@ AmazonS3Service {
UploadFileOnAmazonS3Response copyFile(String fileName, String oldS3Path, String newS3Path);
String extractS3KeyFromUrl(String url);
}

View File

@@ -8,10 +8,7 @@ import net.gepafin.tendermanagement.model.request.ApplicationAmendmentPagination
import net.gepafin.tendermanagement.model.request.ApplicationAmendmentRequest;
import net.gepafin.tendermanagement.model.request.ApplicationAmendmentRequestBean;
import net.gepafin.tendermanagement.model.request.CloseAmendmentRequest;
import net.gepafin.tendermanagement.model.response.ApplicationAmendmentRequestResponse;
import net.gepafin.tendermanagement.model.response.ApplicationAmendmentRequestViewResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.model.response.GetAllAmendmentResponseBean;
import net.gepafin.tendermanagement.model.response.*;
import java.util.List;
@@ -29,6 +26,6 @@ public interface ApplicationAmendmentRequestService {
public List<ApplicationAmendmentRequestResponse> getAmendmentByApplicationId(HttpServletRequest request,Long applicationId,List<ApplicationAmendmentRequestEnum> statuses);
public ApplicationAmendmentRequestResponse updateApplicationAmendmentStatus(HttpServletRequest request, Long applicationAmendmentId, ApplicationAmendmentRequestEnum status);
void sendReminderEmail(HttpServletRequest request,Long amendmentId);
EmailReminderResponse sendReminderEmail(HttpServletRequest request, Long amendmentId);
PageableResponseBean<List<ApplicationAmendmentRequestViewResponse>> getApplicationAmendmentByPaginnation(HttpServletRequest request, Long userId, ApplicationAmendmentPaginationRequestBean amendmentPaginationRequestBean);
}

View File

@@ -1,6 +1,7 @@
package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.model.request.ApplicationPageableRequestBean;
import net.gepafin.tendermanagement.model.request.ApplicationRequest;
@@ -46,4 +47,9 @@ public interface ApplicationService {
PageableResponseBean<List<ApplicationResponse>> getAllApplicationByPagination(HttpServletRequest request, Long callId, Long companyId, ApplicationPageableRequestBean applicationPageableRequestBean);
public ApplicationEntity validateApplicationWithCompany(Long applicationId,Long companyId);
public byte[] exportCsv(HttpServletRequest request, Long callId);
public ApplicationResponse readmitApplication(HttpServletRequest request, Long applicationId);
}

View File

@@ -7,6 +7,7 @@ import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
import net.gepafin.tendermanagement.model.response.AssignedApplicationViewResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
@@ -23,6 +24,6 @@ public interface AssignedApplicationsService {
AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, UpdateAssignedApplicationRequest assignedApplicationsRequest);
AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id);
AssignedApplicationsEntity validateAssignedApplication(Long assignedApplicationId);
PageableResponseBean<List<AssignedApplicationsResponse>> getAllAssignedApplicationsByPagination(HttpServletRequest request, Long userId, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean);
PageableResponseBean<List<AssignedApplicationViewResponse>> getAllAssignedApplicationsByPagination(HttpServletRequest request, Long userId, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean);
AssignedApplicationsResponse updateAssignedApplicationStatus(HttpServletRequest request, Long assignedApplicationId, AssignedApplicationEnum status);
}

View File

@@ -33,7 +33,7 @@ public interface CallService {
byte[] downloadCallDocumentsAsZip(HttpServletRequest request, Long callId);
PageableResponseBean<List<CallDetailsResponseBean>> getAllCallsByPagination(HttpServletRequest request, Long companyId , Boolean onlyPreferredCall,CallPageableRequestBean callPageableRequestBean);
PageableResponseBean<List<CallDetailsResponseBean>> getAllCallsByPagination(HttpServletRequest request, Long companyId , Boolean onlyPreferredCall,Boolean onlyConfidiCall,CallPageableRequestBean callPageableRequestBean);
CallResponse createCallStep2EvaluationV2(HttpServletRequest request, Long callId, CreateCallRequestStep2EvaluationV2 createCallRequest);

View File

@@ -0,0 +1,9 @@
package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.response.EmailResendResponseBean;
public interface ResendEmailService {
EmailResendResponseBean resendEmail(HttpServletRequest request , Long userActionId);
}

View File

@@ -8,9 +8,7 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.model.util.JWTToken;
import java.util.List;
@@ -28,7 +26,7 @@ public interface UserService {
UserEntity validateUser(Long userId);
void initiatePasswordReset(InitiatePasswordResetReq resetReq);
InitiatePasswordResetResponse initiatePasswordReset(InitiatePasswordResetReq resetReq);
Boolean resetPassword(ResetPasswordReq resetPasswordReq);

View File

@@ -0,0 +1,32 @@
package net.gepafin.tendermanagement.service.feignClient;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import java.net.URI;
import java.util.List;
import java.util.Map;
@FeignClient(value = "protocol-service" ,url = GepafinConstant.PROTOCOL_SERVICE_URL)
public interface ProtocolService {
@PostMapping(GepafinConstant.PROTOCOL_SERVICE_BEARER_TOKEN)
ResponseEntity<String> getBearerToken(@RequestHeader HttpHeaders headers,@RequestParam("codAoo") String codAoo,@RequestParam("username") String username,@RequestParam("password") String password
);
@PutMapping(GepafinConstant.PROTOCOL_SERVICE_CREATE_PROTOCOL)
ResponseEntity<Object> createProtocol(@RequestHeader HttpHeaders headers, @RequestParam("CLASSIFICA") String classifica, @RequestParam("ANNO_FASCICOLO") String year, @RequestParam("PROGR_FASCICOLO") String applicationId,
@RequestParam("DES_FASCICOLO") String companyName, @RequestParam("PARENT_DES_FASCICOLO") String callName, @RequestParam("PARENT_PROGR_FASCICOLO") String callId, @RequestBody List<Map<String,Object>> requestBody
);
}

View File

@@ -217,4 +217,9 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
}
}
public String extractS3KeyFromUrl(String url) {
return url.replace(s3Url, "");
}
}

View File

@@ -12,10 +12,7 @@ import net.gepafin.tendermanagement.model.request.ApplicationAmendmentPagination
import net.gepafin.tendermanagement.model.request.ApplicationAmendmentRequest;
import net.gepafin.tendermanagement.model.request.ApplicationAmendmentRequestBean;
import net.gepafin.tendermanagement.model.request.CloseAmendmentRequest;
import net.gepafin.tendermanagement.model.response.ApplicationAmendmentRequestResponse;
import net.gepafin.tendermanagement.model.response.ApplicationAmendmentRequestViewResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.model.response.GetAllAmendmentResponseBean;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.ApplicationAmendmentRequestRepository;
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
import net.gepafin.tendermanagement.service.ApplicationAmendmentRequestService;
@@ -145,17 +142,18 @@ public class ApplicationAmendmentRequestServiceImpl implements ApplicationAmendm
}
@Override
public void sendReminderEmail(HttpServletRequest request,Long amendmentId) {
public EmailReminderResponse sendReminderEmail(HttpServletRequest request, Long amendmentId) {
ApplicationAmendmentRequestEntity amendment = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(amendmentId)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG)));
EmailReminderResponse response = new EmailReminderResponse();
Optional<ApplicationEvaluationEntity> entityOptional = applicationEvaluationRepository.findByIdAndIsDeletedFalse(amendment.getApplicationEvaluationEntity().getId());
if (entityOptional.isPresent()) {
UserEntity user = validator.validatePreInstructor(request, entityOptional.get().getUserId());
applicationAmendmentRequestDao.sendReminderEmail(amendmentId);
response = applicationAmendmentRequestDao.sendReminderEmail(amendmentId);
}
return response;
}
@Override

View File

@@ -11,6 +11,7 @@ import net.gepafin.tendermanagement.model.request.ApplicationEvaluationFormReque
import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationFormResponse;
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationResponse;
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationResponseBean;
import net.gepafin.tendermanagement.model.response.ApplicationEvaluationVersionResponse;
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
import net.gepafin.tendermanagement.service.ApplicationEvaluationService;

View File

@@ -1,11 +1,13 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.ApplicationDao;
import net.gepafin.tendermanagement.dao.FlowFormDao;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.ApplicationPageableRequestBean;
@@ -15,6 +17,7 @@ import net.gepafin.tendermanagement.enums.FormActionEnum;
import net.gepafin.tendermanagement.model.request.ApplicationRequestBean;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.service.ApplicationService;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
@@ -39,6 +42,9 @@ public class ApplicationServiceImpl implements ApplicationService {
@Autowired
private Validator validator;
@Autowired
private CallService callService;
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponseBean createApplication(HttpServletRequest request,
@@ -154,4 +160,20 @@ public class ApplicationServiceImpl implements ApplicationService {
public ApplicationEntity validateApplicationWithCompany(Long applicationId,Long companyId) {
return applicationDao.validateApplicationWithCompany(applicationId,companyId);
}
@Override
public byte[] exportCsv(HttpServletRequest request, Long callId) {
UserEntity userEntity = validator.validateUser(request);
CallEntity call=callService.validateCall(callId);
validator.validateHubId(request,call.getHub().getId());
byte[] csvBytes= applicationDao.exportCsv(callId);
return csvBytes;
}
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponse readmitApplication(HttpServletRequest request, Long applicationId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.readmitApplication(request, applicationId);
}
}

View File

@@ -9,6 +9,7 @@ import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
import net.gepafin.tendermanagement.model.response.AssignedApplicationViewResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.service.AssignedApplicationsService;
@@ -66,7 +67,7 @@ public class AssignedApplicationsServiceImpl implements AssignedApplicationsServ
}
@Override
public PageableResponseBean<List<AssignedApplicationsResponse>> getAllAssignedApplicationsByPagination(HttpServletRequest request, Long userId, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean) {
public PageableResponseBean<List<AssignedApplicationViewResponse>> getAllAssignedApplicationsByPagination(HttpServletRequest request, Long userId, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean) {
UserEntity user=validator.validateUser(request);
return assignedApplicationsDao.getAllAssignedApplicationsByPagination(user,assignedApplicationPageableRequestBean,userId);
}

View File

@@ -15,10 +15,7 @@ import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.*;
import net.gepafin.tendermanagement.model.request.LoginReq;
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.response.LoginResponse;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.LoginAttemptRepository;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
@@ -122,7 +119,7 @@ public class AuthenticationService {
createFailedLoginAttempt(loginAttemptEntity, e.getMessage());
throw e;
}
return getJWTTokenBean(user, loginReq.getRememberMe(), loginAttemptEntity.getId());
return getJWTTokenBean(user, loginReq.getRememberMe(), loginAttemptEntity.getId(),null);
}
public LoginAttemptEntity prepareLoginAttemptEntity(LoginReq loginUserReq, HttpServletRequest request) {
@@ -145,7 +142,7 @@ public class AuthenticationService {
loginAttemptEntity.setErrorMsg(errorMsg);
loginAttemptDao.createLoginAttempt(loginAttemptEntity);
}
public JWTToken getJWTTokenBean(UserEntity user, Boolean rememberMe, Long loginAttemptId) {
public JWTToken getJWTTokenBean(UserEntity user, Boolean rememberMe, Long loginAttemptId, List<EmailSendResponse> emailSendResponse) {
UserEntity oldUserEntity = Utils.getClonedEntityForData(user);
user.setLastLogin(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
user = userRepository.save(user);
@@ -156,7 +153,7 @@ public class AuthenticationService {
LoginResponse loginResponse = getLoginResponse(user, roleResponseBean);
JWTToken jwtToken = new JWTToken(token, loginResponse);
JWTToken jwtToken = new JWTToken(token, loginResponse , emailSendResponse);
/** This code is responsible for adding a version history log for the "Create user Or Update user" operation. **/
loggingUtil.addVersionHistoryWithoutToken(VersionHistoryRequest.builder().request(request).oldData(oldUserEntity).newData(user).actionType(VersionActionTypeEnum.UPDATE).build());
@@ -238,7 +235,7 @@ public class AuthenticationService {
loginAttemptEntity = prepareLoginAttemptEntity(loginReq, request);
loginAttemptEntity.setUserId(userEntity.getId());
LoginAttemptEntity loginAttempt = createSuccessLoginAttempt(loginAttemptEntity);
return getJWTTokenBean(userEntity, Boolean.TRUE, loginAttempt.getId());
return getJWTTokenBean(userEntity, Boolean.TRUE, loginAttempt.getId(),null);
} catch (Exception e) {
log.info("Authentication login failed for email: {}",e.getMessage());
loginAttemptEntity.setUserId(userId);

View File

@@ -105,9 +105,9 @@ public class CallServiceImpl implements CallService {
@Override
@Transactional(rollbackFor = Exception.class)
public PageableResponseBean<List<CallDetailsResponseBean>> getAllCallsByPagination(HttpServletRequest request,Long companyId , Boolean onlyPreferredCall, CallPageableRequestBean callPageableRequestBean) {
public PageableResponseBean<List<CallDetailsResponseBean>> getAllCallsByPagination(HttpServletRequest request,Long companyId , Boolean onlyPreferredCall,Boolean onlyConfidiCall, CallPageableRequestBean callPageableRequestBean) {
UserEntity user = validator.validateUser(request);
return callDao.getAllCallsByPagination(request,user,companyId,onlyPreferredCall,callPageableRequestBean);
return callDao.getAllCallsByPagination(request,user,companyId,onlyPreferredCall,onlyConfidiCall,callPageableRequestBean);
}
@Override
@Transactional(rollbackFor = Exception.class)

View File

@@ -83,7 +83,9 @@ public class CompanyServiceImpl implements CompanyService {
@Override
@Transactional(readOnly = true)
public VatCheckResponseBean checkVatNumber(HttpServletRequest request, String vatNumber) {
return vatCheckDao.checkVatNumber(vatNumber);
UserEntity userEntity = validator.validateUser(request);
Long hubId = userEntity.getHub().getId();
return vatCheckDao.checkVatNumber(vatNumber, hubId);
}
@Override
public CompanyEntity validateCompany(Long companyId) {

View File

@@ -12,13 +12,15 @@ public class EmailServiceFactory {
@Autowired
private MailgunEmailService mailgunEmailService;
@Autowired
private SystemEmailService systemEmailService;
public EmailService getEmailService(String serviceType) {
if ("MAILGUN_SERVICE".equals(serviceType)) {
return mailgunEmailService;
} else if ("PEC_SERVICE".equals(serviceType)) {
return pecEmailService;
} else {
throw new IllegalArgumentException("Invalid email service type: " + serviceType);
}
return switch (serviceType) {
case "PEC_SERVICE" -> pecEmailService;
case "SYSTEM_EMAIL_SERVICE" -> systemEmailService;
default -> mailgunEmailService;
};
}
}

View File

@@ -1,25 +1,32 @@
package net.gepafin.tendermanagement.service.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import lombok.extern.slf4j.Slf4j;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.ApplicationDao;
import net.gepafin.tendermanagement.dao.EmailLogDao;
import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.dao.NotificationDao;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum;
import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailConfig;
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.model.request.NotificationReq;
import net.gepafin.tendermanagement.model.request.PecEmailRequest;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import org.opensaml.xmlsec.signature.G;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
@@ -30,20 +37,26 @@ public class PecEmailService implements EmailService {
@Value("${isPecServiceEnabled}")
private String isPecServiceEnabled;
@Autowired
private Validator validator;
@Autowired
private EmailLogDao emailLogDao;
@Autowired
private NotificationDao notificationDao;
@Autowired
private ApplicationDao applicationDao;
@Override
public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogRequest emailLogRequest) {
if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) {
return;
}
PecEmailRequest emailRequest = new PecEmailRequest();
emailRequest.setSender(emailConfig.getSender());
emailRequest.setSubject(subject);
@@ -67,13 +80,27 @@ public class PecEmailService implements EmailService {
.header("Content-Type", "application/json")
.body(Utils.convertObjectToJson(emailRequest)) // Serialize the emailRequest object to JSON
.asString();
if (!isSuccessfulPecResponse(response2.getBody())) {
String errorMsg = "PEC sending failed: " + response2.getBody();
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE);
emailLogRequest.setErrorMessage(errorMsg);
sendNotificationOnFailure(emailLogRequest.getUserId(),emailLogRequest.getEmailType());
if (EmailScenarioTypeEnum.APPLICATION_SUBMITTED.equals(emailLogRequest.getEmailType())) {
applicationDao.sendApplicationSubmissionFailureEmail(emailLogRequest);
}
}
}
}catch(Exception e) {
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE);
emailLogRequest.setErrorMessage(e.getMessage());
emailLogDao.createEmailLog(emailLogRequest);
throw new RuntimeException("Failed to send email via PEC: " + response2.getStatus());
sendNotificationOnFailure(emailLogRequest.getUserId(),emailLogRequest.getEmailType());
if (EmailScenarioTypeEnum.APPLICATION_SUBMITTED.equals(emailLogRequest.getEmailType())) {
applicationDao.sendApplicationSubmissionFailureEmail(emailLogRequest);
}
}
if(response2 != null) {
emailLogRequest.setEmailServiceResponse(response2.getBody());
@@ -82,6 +109,57 @@ public class PecEmailService implements EmailService {
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE);
emailLogDao.createEmailLog(emailLogRequest);
}
private void sendNotificationOnFailure(Long userId, EmailScenarioTypeEnum emailScenarioTypeEnum) {
if (userId == null) {
log.warn("Cannot send notification: userId is null.");
return;
}
Map<String, String> placeholders = new HashMap<>();
placeholders.put("{{email_scenario}}", emailScenarioTypeEnum.getValue());
NotificationReq notificationReq = notificationDao.createNotificationReq(
NotificationTypeEnum.PEC_EMAIL_SENDING_FAILURE.getValue(),
placeholders,
userId,
null,
null
);
try {
notificationDao.sendNotification(notificationReq);
log.info("Sent PEC failure notification to user {}", userId);
} catch (Exception e) {
log.error("Failed to send PEC failure notification to user {}: {}", userId, e.getMessage());
}
}
private boolean isSuccessfulPecResponse(String responseBody) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
boolean success = jsonNode.has("success") && jsonNode.get("success").asBoolean();
boolean hasNoError = !jsonNode.has("error") || jsonNode.get("error").isNull();
if (jsonNode.has("success") && !success) {
log.error("PEC response indicates failure: {}", responseBody);
return false;
}
if (responseBody.contains("403") || responseBody.toLowerCase().contains("<html") || responseBody.toLowerCase().contains("<!doctype html>")) {
log.error("PEC response is a 403 HTML Forbidden page or invalid format: {}", responseBody);
return false;
}
return success && hasNoError;
} catch (Exception e) {
log.error("Invalid PEC response format: {}", responseBody);
return false;
}
}
}

View File

@@ -0,0 +1,25 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.EmailDao;
import net.gepafin.tendermanagement.model.response.EmailResendResponseBean;
import net.gepafin.tendermanagement.service.ResendEmailService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ResendEmailServiceImpl implements ResendEmailService {
@Autowired
Validator validator;
@Autowired
EmailDao emailDao;
@Override
public EmailResendResponseBean resendEmail(HttpServletRequest request, Long userActionId) {
validator.validateUser(request);
return emailDao.resendEmail(request,userActionId);
}
}

View File

@@ -0,0 +1,86 @@
package net.gepafin.tendermanagement.service.impl;
import com.mailgun.api.v3.MailgunMessagesApi;
import com.mailgun.client.MailgunClient;
import com.mailgun.model.message.MessageResponse;
import net.gepafin.tendermanagement.dao.EmailLogDao;
import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailConfig;
import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class SystemEmailService implements EmailService {
@Value("${mailGun_user}")
public String mailGunUser;
@Value("${mailGun_apiKey}")
public String mailGunApiKey;
@Value("${mailGun_domainName}")
public String mailGunDomainName;
@Value("${mailGun_base_url}")
public String mailGunBaseUrl;
@Value("${isMailSendingEnabled}")
private String isEmailSendingEnabled;
@Autowired
private Validator validator;
@Autowired
private EmailLogDao emailLogDao;
public final Logger log = LoggerFactory.getLogger(SystemEmailService.class);
public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogRequest emailLogRequest) {
if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) {
return;
}
emailLogRequest.setEmailSubject(subject);
emailLogRequest.setEmailBody(body);
emailLogRequest.setSendStatus(StatusTypeEnum.SUCCESS.getValue());
emailLogRequest.setRecipientEmails(Utils.listToCommaSeparatedString(recipientEmails));
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE);
if (Boolean.FALSE.equals(validator.isTestProfileActivated())) {
MessageResponse response = null;
try {
MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(mailGunBaseUrl, mailGunApiKey).createApi(MailgunMessagesApi.class);
String mailFrom = mailGunUser;
com.mailgun.model.message.Message message = com.mailgun.model.message.Message.builder().from(mailFrom).to(recipientEmails).subject(subject).html(body).build();
response = mailgunMessagesApi.sendMessage(mailGunDomainName, message);
} catch (Exception e) {
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE);
emailLogRequest.setErrorMessage(e.getMessage());
emailLogDao.createEmailLog(emailLogRequest);
throw new RuntimeException("Failed to send email via Mailgun: " + (response != null ? response.getMessage() : "No response from Mailgun"), e);
}
if(response != null) {
emailLogRequest.setEmailServiceResponse(response.toString());
}
emailLogDao.createEmailLog(emailLogRequest);
}
}
}

View File

@@ -11,9 +11,7 @@ import net.gepafin.tendermanagement.model.request.UpdateUserReq;
import net.gepafin.tendermanagement.model.request.UserReq;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.LoggingUtil;
@@ -78,8 +76,8 @@ public class UserServiceImpl implements UserService {
}
@Override
public void initiatePasswordReset(InitiatePasswordResetReq resetReq) {
userDao.initiatePasswordReset(resetReq);
public InitiatePasswordResetResponse initiatePasswordReset(InitiatePasswordResetReq resetReq) {
return userDao.initiatePasswordReset(resetReq);
}
@Override

View File

@@ -98,11 +98,19 @@ public class DateTimeUtil {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.parse(dateTimeStr, formatter);
}
public static LocalDateTime parseStringToLocalDateTime(String timestampStr) {
// Use ISO_LOCAL_DATE_TIME to parse the input string
return LocalDateTime.parse(timestampStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
public static LocalDateTime parseStringToLocalDateTime(String dateStr) {
if (dateStr == null || dateStr.isEmpty()) return null;
try {
return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (Exception e) {
try {
return LocalDateTime.parse(dateStr, DateTimeFormatter.ISO_DATE_TIME); // fallback
} catch (Exception ignored) {
}
}
return null;
}
public static String parseLocalTimeToString(LocalTime time, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return time.format(formatter);

View File

@@ -0,0 +1,40 @@
package net.gepafin.tendermanagement.util;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
@Component
public class FileHashUtil {
public static String calculateSHA256(InputStream inputStream) throws IOException {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
try (DigestInputStream dis = new DigestInputStream(inputStream, md)) {
byte[] buffer = new byte[8192];
while (dis.read(buffer) != -1) {
// reading to compute hash
}
}
byte[] digest = md.digest();
return bytesToHex(digest);
} catch (Exception e) {
throw new RuntimeException("Could not generate hash", e);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}

View File

@@ -15,6 +15,7 @@ import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -36,15 +37,18 @@ import jakarta.persistence.criteria.Root;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum;
import net.gepafin.tendermanagement.enums.MatchModeEnum;
import net.gepafin.tendermanagement.model.request.FilterCriteria;
import net.gepafin.tendermanagement.model.request.GlobalFilters;
import net.gepafin.tendermanagement.model.response.EmailSendResponse;
import net.gepafin.tendermanagement.web.rest.api.errors.*;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
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;
@@ -57,6 +61,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import feign.FeignException;
import io.micrometer.common.util.StringUtils;
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;
@@ -291,11 +296,14 @@ public class Utils {
return pattern.matcher(email).matches();
}
// public static String randomKey(Integer range) {
// String data = String.valueOf(System.currentTimeMillis());
// return data.substring(data.length() - range);
//
// }
public static String randomKey(Integer range) {
String data = String.valueOf(System.currentTimeMillis());
return data.substring(data.length() - range);
return UUID.randomUUID().toString().replace("-", "").substring(0, range);
}
public static String convertObjectToJsonString(Object object) {
try {
// Check if the object is a string
@@ -986,5 +994,63 @@ public class Utils {
}
}
}
public static List<Map<String, Object>> convertJsonToListMap(String jsonString) {
try {
if (jsonString == null || jsonString.trim().isEmpty()) {
return Collections.emptyList();
}
ObjectMapper objectMapper = new ObjectMapper();
String unescaped;
// First try: parse as if it's double-encoded (escaped string containing a JSON array)
try {
unescaped = objectMapper.readValue(jsonString, String.class);
} catch (Exception e) {
// If that fails, assume it's already a proper JSON array
unescaped = jsonString;
}
// Now parse the actual JSON array
return objectMapper.readValue(unescaped, new TypeReference<List<Map<String, Object>>>() {});
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
public static List<String> commaSeparatedStringToList(String emails) {
if (emails == null || emails.isEmpty()) {
return new ArrayList<>();
}
return Arrays.stream(emails.split(","))
.map(String::trim)
.collect(Collectors.toList());
}
public static List<EmailSendResponse> mergeEmailSendResponses(List<EmailSendResponse> existingResponses, EmailSendResponse newResponse) {
Map<EmailScenarioTypeEnum, EmailSendResponse> responseMap = Optional.ofNullable(existingResponses)
.orElse(new ArrayList<>())
.stream()
.collect(Collectors.toMap(
EmailSendResponse::getEmailScenario,
Function.identity(),
(oldVal, newVal) -> newVal,
LinkedHashMap::new
));
responseMap.put(newResponse.getEmailScenario(), newResponse);
return new ArrayList<>(responseMap.values());
}
public static HttpHeaders getHeaders(){
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(org.apache.http.HttpHeaders.USER_AGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0");
return headers;
}
}

View File

@@ -183,7 +183,7 @@ public interface ApplicationAmendmentRequestApi {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) }))
})
@PostMapping(value = "/{amendmentId}/reminder", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Response<Void>> sendReminderEmail(HttpServletRequest request,
ResponseEntity<Response<EmailReminderResponse>> sendReminderEmail(HttpServletRequest request,
@Parameter( required = true)
@PathVariable(value = "amendmentId") Long amendmentId);

View File

@@ -2,11 +2,12 @@ package net.gepafin.tendermanagement.web.rest.api;
import java.util.List;
import net.gepafin.tendermanagement.model.request.ApplicationPageableRequestBean;
import net.gepafin.tendermanagement.model.request.NotificationRequestBean;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.*;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -18,10 +19,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.model.request.ApplicationRequest;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.FormActionEnum;
import net.gepafin.tendermanagement.model.request.ApplicationRequestBean;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
@@ -224,5 +223,35 @@ public interface ApplicationApi {
ResponseEntity<Response<PageableResponseBean<List<ApplicationResponse>>>> getAllApplicationByPagination(HttpServletRequest request,@Parameter(description = "The call id", required = false) @RequestParam(value = "callId", required = false) Long callId,
@Parameter(description = "The company id", required = false) @RequestParam(value = "companyId", required = false) Long companyId, @RequestBody ApplicationPageableRequestBean applicationPageableRequestBean);
@Operation(summary = "Api to download application data as a CSV file using the call ID",
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 = "/call/{callId}/csv")
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
public ResponseEntity<byte[]> exportCsv(
HttpServletRequest request, @Parameter(description = "The call id", required = true) @PathVariable(value = "callId", required = true) Long callId);
@Operation(summary = "Api to re-admit an application",
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) })) })
@PutMapping(value = "/{applicationId}/readmit", produces = { "application/json" })
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')|| hasRole('ROLE_INSTRUCTOR_MANAGER')|| hasRole('ROLE_PRE_INSTRUCTOR')")
ResponseEntity<Response<ApplicationResponse>> readmitApplication(HttpServletRequest request,
@Parameter(description = "The application id", required = true) @PathVariable("applicationId") Long applicationId);
}

View File

@@ -12,6 +12,7 @@ import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
import net.gepafin.tendermanagement.model.response.ApplicationResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationViewResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
import net.gepafin.tendermanagement.model.util.Response;
@@ -128,8 +129,8 @@ public interface AssignedApplicationsApi {
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@PostMapping(value = "/pagination", produces = "application/json")
ResponseEntity<Response<PageableResponseBean<List<AssignedApplicationsResponse>>>> getAllAssignedApplicationsByPagination(HttpServletRequest request,
@Parameter(description = "The User ID", required = false) @RequestParam(value = "userId",required = false) Long userId, @RequestBody AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean);
ResponseEntity<Response<PageableResponseBean<List<AssignedApplicationViewResponse>>>> getAllAssignedApplicationsByPagination(HttpServletRequest request,
@Parameter(description = "The User ID", required = false) @RequestParam(value = "userId",required = false) Long userId, @RequestBody AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean);
}

Some files were not shown because too many files have changed in this diff Show More