Resolved Conflicts
This commit is contained in:
@@ -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);
|
||||
@@ -301,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;
|
||||
}
|
||||
@@ -361,6 +378,7 @@ 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());
|
||||
@@ -510,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());
|
||||
@@ -651,9 +670,9 @@ 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) {
|
||||
@@ -1043,7 +1062,7 @@ 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(
|
||||
@@ -1055,17 +1074,18 @@ public class ApplicationAmendmentRequestDao {
|
||||
// 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);
|
||||
@@ -1095,6 +1115,8 @@ public class ApplicationAmendmentRequestDao {
|
||||
existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getId());
|
||||
|
||||
AssignedApplicationsEntity oldAssignedApplicationData = Utils.getClonedEntityForData(assignedApplicationsEntity);
|
||||
existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().setStatus(AssignedApplicationEnum.OPEN.getValue());
|
||||
|
||||
assignedApplicationsEntity = assignedApplicationsRepository.save(existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity());
|
||||
log.info("Updated AssignedApplication status to OPEN for ID: {}", assignedApplicationsEntity.getId());
|
||||
|
||||
@@ -1121,16 +1143,18 @@ public class ApplicationAmendmentRequestDao {
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
public ApplicationAmendmentRequestResponse extendResponseDays(Long id, Long newResponseDays) {
|
||||
log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays);
|
||||
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
|
||||
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. **/
|
||||
@@ -1187,7 +1211,7 @@ 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(() -> { log.error("Amendment not found with ID: {}", amendmentId);
|
||||
@@ -1195,6 +1219,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
});
|
||||
|
||||
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());
|
||||
@@ -1208,12 +1233,22 @@ public class ApplicationAmendmentRequestDao {
|
||||
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) {
|
||||
@@ -1243,29 +1278,26 @@ public class ApplicationAmendmentRequestDao {
|
||||
return Utils.replacePlaceholders(template.getHtmlContent(), bodyPlaceholders);
|
||||
}
|
||||
|
||||
public ApplicationEvaluationEntity calculateEndDateAndSuspensionDays(ApplicationEvaluationEntity applicationEvaluationEntity){
|
||||
log.info("Calculating end date and suspension days for Application Evaluation ID: {}", applicationEvaluationEntity.getId());
|
||||
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);
|
||||
log.debug("Updated suspended days: {}", applicationEvaluationEntity.getSuspendedDays());
|
||||
ApplicationEvaluationEntity applicationEvaluation = applicationEvaluationRepository.save(applicationEvaluationEntity);
|
||||
|
||||
log.info("Application Evaluation updated successfully. ID: {}", applicationEvaluation.getId());
|
||||
/** 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();
|
||||
@@ -1572,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.*;
|
||||
@@ -23,15 +28,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;
|
||||
@@ -49,17 +53,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;
|
||||
@@ -69,7 +73,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 {
|
||||
@@ -133,6 +136,9 @@ public class ApplicationDao {
|
||||
@Value("${call.id}")
|
||||
private String callId;
|
||||
|
||||
@Value("${sviluppumbriaUuid}")
|
||||
private String sviluppumbriaUuid;
|
||||
|
||||
@Autowired
|
||||
private AmazonS3Service amazonS3Service;
|
||||
|
||||
@@ -196,6 +202,16 @@ 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);
|
||||
@@ -952,16 +968,20 @@ public class ApplicationDao {
|
||||
}
|
||||
}
|
||||
|
||||
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())) {
|
||||
@@ -973,11 +993,25 @@ public class ApplicationDao {
|
||||
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);
|
||||
@@ -988,16 +1022,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);
|
||||
@@ -1099,10 +1135,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());
|
||||
@@ -1130,7 +1165,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<>();
|
||||
@@ -1179,24 +1214,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())
|
||||
@@ -1225,6 +1242,12 @@ public class ApplicationDao {
|
||||
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();
|
||||
@@ -1232,6 +1255,7 @@ public class ApplicationDao {
|
||||
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. **/
|
||||
@@ -1307,6 +1331,7 @@ public class ApplicationDao {
|
||||
.setStatus(ApplicationSignedDocumentStatusEnum.valueOf(applicationSignedDocument.getStatus()));
|
||||
applicationSignedDocumentResponse.setCreatedDate(applicationSignedDocument.getCreatedDate());
|
||||
applicationSignedDocumentResponse.setUpdatedDate(applicationSignedDocument.getUpdatedDate());
|
||||
applicationSignedDocumentResponse.setFileHash(applicationSignedDocument.getFileHash());
|
||||
return applicationSignedDocumentResponse;
|
||||
}
|
||||
|
||||
@@ -1885,4 +1910,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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -704,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);
|
||||
|
||||
@@ -1136,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<>();
|
||||
@@ -1683,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()) {
|
||||
@@ -1897,7 +1907,7 @@ public class ApplicationEvaluationDao {
|
||||
assignedApplicationsEntity.getId());
|
||||
ApplicationEvaluationEntity entity;
|
||||
|
||||
|
||||
EmailSendResponse emailSendResponse = new EmailSendResponse();
|
||||
if (existingEntityOptional.isPresent()) {
|
||||
ApplicationEvaluationEntity existingEntity = existingEntityOptional.get();
|
||||
// UserEntity userEntity = userService.validateUser(application.getUserId());
|
||||
@@ -1905,10 +1915,16 @@ 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()))){
|
||||
@@ -1960,27 +1976,48 @@ 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
|
||||
@@ -2040,6 +2077,7 @@ public class ApplicationEvaluationDao {
|
||||
|
||||
ApplicationEvaluationEntity entity = applicationEvaluationService.validateApplicationEvaluation(evaluationResponse.getId());
|
||||
|
||||
|
||||
//Handling Application Evaluation form
|
||||
EvaluationFormEntity evaluationFormEntity = evaluationFormService.validateEvaluationForm(evaluationFormId);
|
||||
validateFormFields(applicationEvaluationFormRequestBean,evaluationFormEntity);
|
||||
@@ -2048,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) {
|
||||
@@ -2300,6 +2340,7 @@ public class ApplicationEvaluationDao {
|
||||
}
|
||||
response.setCompanyVatNumber(company.getVatNumber());
|
||||
response.setCompanyCodiceAteco(company.getCodiceAteco());
|
||||
response.setEmailSendResponse(evaluationEntity.getEmailSendResponse());
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<>();
|
||||
@@ -174,10 +183,182 @@ public class AppointmentDao {
|
||||
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);
|
||||
@@ -189,7 +370,6 @@ public class AppointmentDao {
|
||||
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());
|
||||
@@ -202,55 +382,53 @@ public class AppointmentDao {
|
||||
}
|
||||
}
|
||||
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) {
|
||||
log.warn("Received 403 Forbidden from Odessa. Attempting to parse error response.");
|
||||
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);
|
||||
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));
|
||||
}
|
||||
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("Unexpected exception during Odessa login. HubId: {}, Error: {}", hub.getId(), 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) {
|
||||
@@ -300,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);
|
||||
@@ -349,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;
|
||||
}
|
||||
@@ -399,9 +581,12 @@ 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());
|
||||
}
|
||||
|
||||
@@ -420,7 +605,7 @@ public class AppointmentDao {
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
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("Error while fetching Visura list | ApplicationId: {}, HubId: {}, Error: {}", application.getId(), hub.getId(), e.getMessage(), e);
|
||||
@@ -428,86 +613,6 @@ public class AppointmentDao {
|
||||
}
|
||||
}
|
||||
|
||||
private HubEntity authenticateAndSaveToken(HubEntity hub) {
|
||||
|
||||
try {
|
||||
log.info("Starting authentication to Odessa | HubId: {}", hub.getId());
|
||||
//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 {
|
||||
log.error("Login response missing tokenId | HubId: {}", hub.getId());
|
||||
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("403 Forbidden during Odessa login | HubId: {}", hub.getId());
|
||||
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())) {
|
||||
log.warn("Odessa password expired detected in login response | HubId: {}", hub.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())) {
|
||||
throw new CustomValidationException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PASSWORD_EXPIRED_LOGIN_TO_ODESSA));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error parsing forbidden JSON response | HubId: {}, Error: {}", hub.getId(), e.getMessage(), e);
|
||||
}
|
||||
|
||||
// Regenerate the token and retry
|
||||
regenerateTokenAndSave(hub);
|
||||
} catch (Exception e) {
|
||||
log.error("Unexpected error during Odessa authentication | HubId: {}, Error: {}", hub.getId(), 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 {
|
||||
@@ -523,7 +628,7 @@ public class AppointmentDao {
|
||||
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("Error during NDG retrieval | ApplicationId: {}, HubId: {}, Message: {}", application.getId(), hub.getId(), e.getMessage(), e);
|
||||
@@ -531,9 +636,10 @@ public class AppointmentDao {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -546,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());
|
||||
@@ -719,9 +825,8 @@ public class AppointmentDao {
|
||||
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);
|
||||
@@ -741,9 +846,11 @@ 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);
|
||||
|
||||
@@ -764,8 +871,8 @@ public class AppointmentDao {
|
||||
return appointmentCreationResponse;
|
||||
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
log.error("403 Forbidden received while retrieving template. Attempting to regenerate token and retry. Application ID: {}", applicationId);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -773,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;
|
||||
@@ -808,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);
|
||||
@@ -883,13 +1010,40 @@ public class AppointmentDao {
|
||||
// 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();
|
||||
@@ -909,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 {
|
||||
@@ -929,8 +1084,8 @@ public class AppointmentDao {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void uploadDocumentToExternalSystemSync(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
|
||||
log.info("Starting sync document upload for documentId: {}", documentId);
|
||||
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);
|
||||
|
||||
@@ -971,9 +1126,9 @@ public class AppointmentDao {
|
||||
|
||||
log.info("Document uploaded successfully to external system: {}", parsedResponse);
|
||||
} catch (FeignException.Forbidden forbiddenException) {
|
||||
log.error("403 Forbidden from external system during upload for documentId: {}. Retrying with new token...", documentId);
|
||||
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));
|
||||
@@ -1004,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);
|
||||
}
|
||||
|
||||
@@ -1017,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("/");
|
||||
|
||||
@@ -332,7 +332,8 @@ public class AssignedApplicationsDao {
|
||||
if (pageNo == null || pageNo <= 0) {
|
||||
pageNo = GepafinConstant.DEFAULT_PAGE;
|
||||
}
|
||||
Specification<AssignedApplicationsView> spec = searchByPagination( assignedApplicationPageableRequestBean, user,userId);
|
||||
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
|
||||
|
||||
@@ -350,10 +351,10 @@ public class AssignedApplicationsDao {
|
||||
return pageableResponseBean;
|
||||
}
|
||||
|
||||
public Specification<AssignedApplicationsView> 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
|
||||
@@ -394,7 +395,7 @@ public class AssignedApplicationsDao {
|
||||
|
||||
|
||||
private List<Predicate> getPredicates(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,
|
||||
CriteriaBuilder criteriaBuilder, Root<AssignedApplicationsView> root, UserEntity userEntity,Long userId) {
|
||||
CriteriaBuilder criteriaBuilder, Root<AssignedApplicationsView> root,Long hubId,Long userId) {
|
||||
|
||||
Integer year = null;
|
||||
String search = null;
|
||||
@@ -465,6 +466,8 @@ public class AssignedApplicationsDao {
|
||||
}
|
||||
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
|
||||
|
||||
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.HUB_ID), hubId));
|
||||
|
||||
Utils.applyFiltersByPagination(root, criteriaBuilder, predicates, filters);
|
||||
|
||||
return predicates;
|
||||
@@ -487,6 +490,7 @@ public class AssignedApplicationsDao {
|
||||
response.setCompanyName(view.getCompanyName());
|
||||
response.setCreatedDate(view.getCreatedDate());
|
||||
response.setUpdatedDate(view.getUpdatedDate());
|
||||
response.setEmailSendResponse(view.getEmailSendResponse());
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@@ -1039,7 +1039,7 @@ 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;
|
||||
@@ -1060,7 +1060,7 @@ 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);
|
||||
@@ -1111,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
|
||||
@@ -1138,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<>();
|
||||
@@ -1192,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()) {
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -105,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,
|
||||
@@ -173,7 +173,7 @@ public class CompanyDao {
|
||||
entity.setHub(userEntity.getHub());
|
||||
entity.setJson(Utils.convertMapIntoJsonString(request.getVatCheckResponse()));
|
||||
updateCodiceAtecoFieldWithNewJson(entity);
|
||||
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
@@ -498,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);
|
||||
}
|
||||
@@ -532,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) {
|
||||
@@ -561,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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
212
src/main/java/net/gepafin/tendermanagement/dao/EmailDao.java
Normal file
212
src/main/java/net/gepafin/tendermanagement/dao/EmailDao.java
Normal 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
// }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user