Merge pull request #371 from Kitzanos/develop

Sync Master with Develop (17/11/2025)
This commit is contained in:
Rinaldo
2025-11-17 11:20:10 +01:00
committed by GitHub
59 changed files with 1702 additions and 256 deletions

View File

@@ -577,6 +577,7 @@ public class GepafinConstant {
public static final String CREATE_NDG="CHECK_OR_CREATE_NDG_CODE"; public static final String CREATE_NDG="CHECK_OR_CREATE_NDG_CODE";
public static final String NDG_NOT_FOUND="ndg.not.found"; public static final String NDG_NOT_FOUND="ndg.not.found";
public static final String EMAIL_PEC_REQUIRED="email.pec.cannot.null"; public static final String EMAIL_PEC_REQUIRED="email.pec.cannot.null";
public static final String COMPANY_NAME_JSON="denominazione";
public static final String USER_REQUEST_COMPLETED="user.request.completed"; public static final String USER_REQUEST_COMPLETED="user.request.completed";
public static final String END_DATE_GREATER_THAN_NOW="end.date.greater.than.now"; public static final String END_DATE_GREATER_THAN_NOW="end.date.greater.than.now";
public static final String PEC_EMAIL_IS_REQUIRED = "pec.email.required"; public static final String PEC_EMAIL_IS_REQUIRED = "pec.email.required";
@@ -622,6 +623,17 @@ public class GepafinConstant {
public static final List<String> MANUAL_EMAIL_KEYS = Arrays.asList(SUBJECT, MESSAGE); public static final List<String> MANUAL_EMAIL_KEYS = Arrays.asList(SUBJECT, MESSAGE);
public static final String INVALID_EMAIL_JSON = "invalid.email.json"; public static final String INVALID_EMAIL_JSON = "invalid.email.json";
public static final String MORE_FIELDS_REQUIRED_FOR_REJECTION="more.fields.required"; public static final String MORE_FIELDS_REQUIRED_FOR_REJECTION="more.fields.required";
public static final String CREATE_APPLICATION_CONTRACT="create.application.contract";
public static final String APPLICATION_CONTRACT_NOT_FOUND="application.contract.not.found";
public static final String APPLICATION_CONTRACT_FETCHED="application.contract.fetched";
public static final String APPLICATION_CONTRACT_UPDATED="application.contract.updated";
public static final String FILES_REQUIRED_FOR_CONTRACT="files.required.for.contract";
public static final String APPLICATION_CONTRACT_ALREADY_EXIST="application.contract.already.exist";
public static final String APPLICATION_NOT_APPROVED="application.not.approved";
public static final String SUBJECT_AND_BODY_REQUIRED="subject.body.required";
public static final String MAIL_SENT_SUCCESSFULLY="mail.send.successfully";
public static final String EMAIL_LOG_FETCHED="email.log.fetched";
public static final String APPLICATION_AMENDMENT_APPROPIATE_STATUS="amendment.appropiate.status";
} }

View File

@@ -671,7 +671,7 @@ public class ApplicationAmendmentRequestDao {
response.setApplicationFormFields(fileDetails); response.setApplicationFormFields(fileDetails);
} }
private List<DocumentResponseBean> getDocumentResponseBean(String documentId) { public List<DocumentResponseBean> getDocumentResponseBean(String documentId) {
List<Long> documentIds = extractIds(documentId); List<Long> documentIds = extractIds(documentId);
List<DocumentResponseBean> documentResponseBeans = documentIds.stream() List<DocumentResponseBean> documentResponseBeans = documentIds.stream()
.map(id -> { .map(id -> {
@@ -1130,8 +1130,12 @@ public class ApplicationAmendmentRequestDao {
public ApplicationAmendmentRequestResponse closeAmendmentRequest(Long id, CloseAmendmentRequest closeAmendmentRequest) { public ApplicationAmendmentRequestResponse closeAmendmentRequest(Long id, CloseAmendmentRequest closeAmendmentRequest) {
log.info("Closing application amendement with ID: {}", id); log.info("Closing application amendement with ID: {}", id);
ApplicationAmendmentRequestEntity existingApplicationAmendment = validatApplicationAmendmentRequestByListStatus(id,List.of(ApplicationAmendmentRequestEnum.AWAITING.getValue(),ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue())); ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
//cloned entity for old data and versioning //cloned entity for old data and versioning
if(Boolean.TRUE.equals(existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()))
|| Boolean.TRUE.equals(existingApplicationAmendment.getStatus().equals(ApplicationAmendmentRequestEnum.EXPIRED.getValue()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_APPROPIATE_STATUS));
}
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment); ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment);
List<ApplicationAmendmentRequestEntity> amendmentRequestList = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse( List<ApplicationAmendmentRequestEntity> amendmentRequestList = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
existingApplicationAmendment.getApplicationEvaluationEntity().getId() existingApplicationAmendment.getApplicationEvaluationEntity().getId()
@@ -1215,7 +1219,11 @@ public class ApplicationAmendmentRequestDao {
public ApplicationAmendmentRequestResponse extendResponseDays(Long id, Long newResponseDays) { public ApplicationAmendmentRequestResponse extendResponseDays(Long id, Long newResponseDays) {
log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays); log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays);
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validatApplicationAmendmentRequestByStatus(id,ApplicationAmendmentRequestEnum.EXPIRED.getValue()); ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
if(Boolean.TRUE.equals(applicationAmendmentRequestEntity.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()))
|| Boolean.TRUE.equals(applicationAmendmentRequestEntity.getStatus().equals(ApplicationAmendmentRequestEnum.AWAITING.getValue()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_APPROPIATE_STATUS));
}
log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays); log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays);
if (newResponseDays != null && newResponseDays > 0) { if (newResponseDays != null && newResponseDays > 0) {
@@ -1304,8 +1312,9 @@ public class ApplicationAmendmentRequestDao {
if (Boolean.TRUE.equals(amendment.getIsEmail()) && email != null && !email.isEmpty()) { if (Boolean.TRUE.equals(amendment.getIsEmail()) && email != null && !email.isEmpty()) {
log.info("Sending reminder email to: {}", email); log.info("Sending reminder email to: {}", email);
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, beneficiaryUser.getId(), email, EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, beneficiaryUser.getId(), email,
beneficiaryUser.getId(), applicationEntity.getId(), amendment.getId(), applicationEntity.getCall().getId()); beneficiaryUser.getId(), applicationEntity.getId(), amendment.getId(), applicationEntity.getCall().getId(),subject,body);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email), emailLogRequest); EmailLogEntity emailLog=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email), emailLog);
EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request); EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
List<EmailSendResponse> responses = List.of(emailSendResponse); List<EmailSendResponse> responses = List.of(emailSendResponse);
if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){ if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
@@ -1776,14 +1785,14 @@ public class ApplicationAmendmentRequestDao {
amendment.setEmailSendResponse(mergedResponses); amendment.setEmailSendResponse(mergedResponses);
applicationAmendmentRequestRepository.save(amendment); applicationAmendmentRequestRepository.save(amendment);
} }
public ApplicationAmendmentRequestEntity validatApplicationAmendmentRequestByListStatus(Long id,List<String> status) { // public ApplicationAmendmentRequestEntity validatApplicationAmendmentRequestByListStatus(Long id,List<String> status) {
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalseAndStatusIn(id, status); // ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(id, status);
if (applicationAmendmentRequestEntity == null) { // if (applicationAmendmentRequestEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND, // throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG)); // Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG));
} // }
return applicationAmendmentRequestEntity; // return applicationAmendmentRequestEntity;
} // }
public long calculateSuspendedDays(List<ApplicationAmendmentRequestEntity> amendments) { public long calculateSuspendedDays(List<ApplicationAmendmentRequestEntity> amendments) {
List<Pair<LocalDateTime, LocalDateTime>> periods = amendments.stream() List<Pair<LocalDateTime, LocalDateTime>> periods = amendments.stream()
.filter(amendmentRequest -> amendmentRequest.getStartDate() != null) .filter(amendmentRequest -> amendmentRequest.getStartDate() != null)

View File

@@ -0,0 +1,248 @@
package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.enums.*;
import net.gepafin.tendermanagement.model.request.ApplicationContractRequest;
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
import net.gepafin.tendermanagement.model.response.ApplicationContractResponse;
import net.gepafin.tendermanagement.model.response.DocumentResponseBean;
import net.gepafin.tendermanagement.repositories.ApplicationContractRepository;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class ApplicationContractDao {
@Autowired
private ApplicationDao applicationDao;
@Autowired
private DocumentDao documentDao;
@Autowired
private ApplicationContractRepository applicationContractRepository;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private HttpServletRequest request;
@Autowired
private LoggingUtil loggingUtil;
@Autowired
private ApplicationAmendmentRequestDao applicationAmendmentRequestDao;
@Autowired
private EmailNotificationDao emailNotificationDao;
@Autowired
private ApplicationEvaluationDao applicationEvaluationDao;
@Autowired
private NotificationDao notificationDao;
@Autowired
private UserService userService;
@Autowired
private AssignedApplicationsRepository assignedApplicationsRepository;
public ApplicationContractResponse createApplicationContract(Long applicationId, List<MultipartFile> contractDocuments,UserEntity user) {
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationId);
Optional<AssignedApplicationsEntity> optionalAssignedApplicationsEntity=assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId());
AssignedApplicationsEntity assignedApplicationsEntity=optionalAssignedApplicationsEntity.get();
AssignedApplicationsEntity oldAssignedApplicationEntity=Utils.getClonedEntityForData(assignedApplicationsEntity);
if (Boolean.FALSE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.APPROVED.getValue()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.APPLICATION_NOT_APPROVED));
}
ApplicationEntity oldApplicationData = Utils.getClonedEntityForData(applicationEntity);
ApplicationContractEntity existingApplicationContractEntity = applicationContractRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
if (existingApplicationContractEntity != null) {
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.APPLICATION_CONTRACT_ALREADY_EXIST));
}
ApplicationContractEntity applicationContractEntity = createApplicationContractEntity(user, applicationEntity);
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(applicationContractEntity).build());
List<DocumentResponseBean> documentResponseBeans = setBeneficiaryContractDocuments(contractDocuments, user, applicationContractEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.CONTRACT_SIGNED.getValue());
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CONTRACT_SIGNED.getValue());
applicationContractEntity.setCompletionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
applicationRepository.save(applicationEntity);
assignedApplicationsRepository.save(assignedApplicationsEntity);
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationData).newData(applicationEntity).build());
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplicationEntity).newData(assignedApplicationsEntity).build());
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("{{call_name}}", applicationEntity.getCall().getName());
String protocolNumber = applicationEntity.getProtocol().getExternalProtocolNumber();
if (protocolNumber == null) {
protocolNumber = String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
}
placeHolders.put("{{protocol_number}}", protocolNumber);
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationDao.validateApplicationEvaluation(applicationEntity.getApplicationEvaluationId());
notificationDao.sendNotificationToInstructor(placeHolders, applicationEvaluationEntity, NotificationTypeEnum.CONTRACT_UPLOAD);
return createApplicationContractResponse(applicationContractEntity, null, documentResponseBeans,applicationEntity.getCall().getName());
}
private ApplicationContractResponse createApplicationContractResponse(ApplicationContractEntity applicationContractEntity, List<DocumentResponseBean> instructorDocuments, List<DocumentResponseBean> beneficiaryDocuments,String callName) {
ApplicationContractResponse applicationContractResponse = new ApplicationContractResponse();
applicationContractResponse.setId(applicationContractEntity.getId());
applicationContractResponse.setInstructorId(applicationContractEntity.getInstructorId());
applicationContractResponse.setStatus(ApplicationContractStatusEnum.valueOf(applicationContractEntity.getStatus()));
applicationContractResponse.setBeneficiaryDocuments(beneficiaryDocuments);
applicationContractResponse.setCompletionDate(applicationContractEntity.getCompletionDate());
applicationContractResponse.setBeneficiaryUserId(applicationContractEntity.getBeneficiaryUserId());
applicationContractResponse.setApplicationId(applicationContractEntity.getApplicationId());
applicationContractResponse.setCallName(callName);
return applicationContractResponse;
}
private List<DocumentResponseBean> setContractDocuments(List<MultipartFile> contractDocuments, UserEntity user, ApplicationContractEntity applicationContractEntity) {
List<DocumentResponseBean> documentResponseBeans = uploadContractDocument(user.getId(), contractDocuments, applicationContractEntity.getId());
List<Long> contractDocumentIds = documentResponseBeans.stream()
.map(DocumentResponseBean::getId)
.collect(Collectors.toList());
String contractDocumentId = contractDocumentIds.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
applicationContractEntity.setInstructorDocument(contractDocumentId);
applicationContractRepository.save(applicationContractEntity);
return documentResponseBeans;
}
private ApplicationContractEntity createApplicationContractEntity(UserEntity user, ApplicationEntity applicationEntity) {
ApplicationContractEntity applicationContractEntity = new ApplicationContractEntity();
applicationContractEntity.setApplicationId(applicationEntity.getId());
applicationContractEntity.setInstructorId(user.getId());
applicationContractEntity.setIsDeleted(Boolean.FALSE);
applicationContractEntity.setApplicationId(applicationEntity.getId());
applicationContractEntity.setStatus(ApplicationContractStatusEnum.SIGNED.getValue());
applicationContractEntity.setBeneficiaryUserId(applicationEntity.getUserId());
applicationContractRepository.save(applicationContractEntity);
return applicationContractEntity;
}
public List<DocumentResponseBean> uploadContractDocument(Long userId, List<MultipartFile> files, Long applicationContractId) {
if (files != null) {
return documentDao.uploadFiles(userId, files, applicationContractId, DocumentSourceTypeEnum.CONTRACT, DocumentTypeEnum.DOCUMENT);
}
return new ArrayList<>();
}
// public ApplicationContractResponse updateApplicationContract(Long applicationContractId, List<MultipartFile> beneficiaryContractDocuments, UserEntity user) {
// ApplicationContractEntity applicationContractEntity = validateApplicationContract(applicationContractId);
// ApplicationContractEntity oldApplicationContract = Utils.getClonedEntityForData(applicationContractEntity);
// applicationContractEntity.setCompletionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
// applicationContractEntity.setStatus(ApplicationContractStatusEnum.SIGNED.getValue());
// List<DocumentResponseBean> beneficiaryContractDocuments1 = setBeneficiaryContractDocuments(beneficiaryContractDocuments, user, applicationContractEntity);
// List<DocumentResponseBean> documentResponseBeans = applicationAmendmentRequestDao.getDocumentResponseBean(applicationContractEntity.getInstructorDocument());
// loggingUtil.addVersionHistory(
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationContract).newData(applicationContractEntity).build());
// ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationContractEntity.getApplicationId());
// ApplicationEntity oldApplicationData = Utils.getClonedEntityForData(applicationEntity);
// Optional<AssignedApplicationsEntity> optionalAssignedApplicationsEntity=assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId());
// AssignedApplicationsEntity assignedApplicationsEntity=optionalAssignedApplicationsEntity.get();
// AssignedApplicationsEntity oldAssignedApplicationEntity=Utils.getClonedEntityForData(assignedApplicationsEntity);
// ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationDao.validateApplicationEvaluation(applicationEntity.getApplicationEvaluationId());
// applicationEntity.setStatus(ApplicationStatusTypeEnum.CONTRACT_SIGNED.getValue());
// assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CONTRACT_SIGNED.getValue());
// applicationRepository.save(applicationEntity);
// assignedApplicationsRepository.save(assignedApplicationsEntity);
// loggingUtil.addVersionHistory(
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationData).newData(applicationEntity).build());
// loggingUtil.addVersionHistory(
// VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApplicationEntity).newData(assignedApplicationsEntity).build());
// Map<String, String> placeHolders = new HashMap<>();
// placeHolders.put("{{call_name}}", applicationEntity.getCall().getName());
// String protocolNumber = applicationEntity.getProtocol().getExternalProtocolNumber();
// if (protocolNumber == null) {
// protocolNumber = String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
// }
// placeHolders.put("{{protocol_number}}", protocolNumber);
// notificationDao.sendNotificationToInstructor(placeHolders, applicationEvaluationEntity, NotificationTypeEnum.CONTRACT_UPLOAD);
//
// return createApplicationContractResponse(applicationContractEntity, documentResponseBeans, beneficiaryContractDocuments1,applicationEntity.getCall().getName());
// }
public ApplicationContractEntity validateApplicationContract(Long applicationContractId) {
ApplicationContractEntity applicationContractEntity = applicationContractRepository.findByIdAndIsDeletedFalse(applicationContractId);
if (applicationContractEntity == null) {
throw new CustomValidationException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_CONTRACT_NOT_FOUND));
}
return applicationContractEntity;
}
private List<DocumentResponseBean> setBeneficiaryContractDocuments(List<MultipartFile> contractDocuments, UserEntity user, ApplicationContractEntity applicationContractEntity) {
List<DocumentResponseBean> documentResponseBeans = uploadContractDocument(user.getId(), contractDocuments, applicationContractEntity.getId());
List<Long> contractDocumentIds = documentResponseBeans.stream()
.map(DocumentResponseBean::getId)
.collect(Collectors.toList());
String contractDocumentId = contractDocumentIds.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
ApplicationContractEntity oldApplicationContractEntity = Utils.getClonedEntityForData(applicationContractEntity);
applicationContractEntity.setBeneficiaryDocument(contractDocumentId);
applicationContractRepository.save(applicationContractEntity);
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationContractEntity).newData(applicationContractEntity).build());
return documentResponseBeans;
}
public ApplicationContractResponse getContractById(Long contractId) {
ApplicationContractEntity applicationContractEntity = validateApplicationContract(contractId);
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationContractEntity.getApplicationId());
return createApplicationContractResponseFromEntity(applicationContractEntity,applicationEntity.getCall().getName());
}
private ApplicationContractResponse createApplicationContractResponseFromEntity(ApplicationContractEntity applicationContractEntity,String callName) {
List<DocumentResponseBean> instructorDocuments = applicationAmendmentRequestDao.getDocumentResponseBean(applicationContractEntity.getInstructorDocument());
List<DocumentResponseBean> beneficiaryDocuments = applicationAmendmentRequestDao.getDocumentResponseBean(applicationContractEntity.getBeneficiaryDocument());
return createApplicationContractResponse(applicationContractEntity, instructorDocuments, beneficiaryDocuments,callName);
}
public ApplicationContractResponse getContractByApplicationId(Long applicationId) {
ApplicationContractEntity applicationContractEntity = applicationContractRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
if (applicationContractEntity == null) {
return null;
}
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationContractEntity.getApplicationId());
return createApplicationContractResponseFromEntity(applicationContractEntity,applicationEntity.getCall().getName());
}
public List<ApplicationContractResponse> getContractByBeneficiaryUserId(UserEntity user) {
List<ApplicationContractEntity> applicationContractEntities = applicationContractRepository.findByBeneficiaryUserIdAndStatusAndIsDeletedFalse(user.getId(), ApplicationContractStatusEnum.SIGNED.getValue());
if (applicationContractEntities.isEmpty()) {
return null;
}
List<ApplicationContractResponse> applicationContractResponses = new ArrayList<>();
for (ApplicationContractEntity applicationContractEntity : applicationContractEntities) {
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationContractEntity.getApplicationId());
ApplicationContractResponse applicationContractResponse = createApplicationContractResponseFromEntity(applicationContractEntity,applicationEntity.getCall().getName());
applicationContractResponses.add(applicationContractResponse);
}
return applicationContractResponses;
}
}

View File

@@ -229,6 +229,9 @@ public class ApplicationDao {
@Autowired @Autowired
private SystemEmailTemplatesDao systemEmailTemplatesDao; private SystemEmailTemplatesDao systemEmailTemplatesDao;
@Autowired
private ApplicationContractRepository applicationContractRepository;
public final Random random = new Random(); public final Random random = new Random();
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) { public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
@@ -1065,9 +1068,9 @@ public class ApplicationDao {
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true); ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true);
protocolDao.saveProtocolEntity(protocolEntity); protocolDao.saveProtocolEntity(protocolEntity);
applicationEntity.setProtocol(protocolEntity); applicationEntity.setProtocol(protocolEntity);
if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(sviluppumbriaUuid))) { // if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(sviluppumbriaUuid))) {
protocolEntity = protocolDao.createExternalProtocol(applicationEntity, company, protocolEntity); // protocolEntity = protocolDao.createExternalProtocol(applicationEntity, company, protocolEntity);
} // }
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue()); applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(protocolEntity.getCreatedDate()); applicationEntity.setSubmissionDate(protocolEntity.getCreatedDate());
applicationEntity = applicationRepository.save(applicationEntity); applicationEntity = applicationRepository.save(applicationEntity);
@@ -1229,7 +1232,7 @@ public class ApplicationDao {
// Replace placeholders in the subject and body // Replace placeholders in the subject and body
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders); String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders); String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.USER,userEntity.getId(),userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId()); EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.USER,userEntity.getId(),userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId(),subject,body);
String email = userEntity.getEmail(); String email = userEntity.getEmail();
if (userEntity.getBeneficiary() != null) { if (userEntity.getBeneficiary() != null) {
emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY); emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY);
@@ -1242,12 +1245,14 @@ public class ApplicationDao {
} }
emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId()); emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId());
} }
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogEntity);
if (Boolean.TRUE.equals(hub.getUniqueUuid().equals(defaultHubUuid)) && userEntity.getBeneficiary() != null) { if (Boolean.TRUE.equals(hub.getUniqueUuid().equals(defaultHubUuid)) && userEntity.getBeneficiary() != null) {
emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY); emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY);
email = userEntity.getBeneficiary().getEmail(); email = userEntity.getBeneficiary().getEmail();
emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId()); emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId());
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogRequest); EmailLogEntity emailLog=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLog);
} }
List<String> recipientEmails = new ArrayList<>(); List<String> recipientEmails = new ArrayList<>();
// recipientEmails.add(email); // recipientEmails.add(email);
@@ -1274,7 +1279,8 @@ public class ApplicationDao {
emailLogRequest.setRecipientType(RecipientTypeEnum.COMPANY); emailLogRequest.setRecipientType(RecipientTypeEnum.COMPANY);
emailLogRequest.setRecipientEmails(String.valueOf(recipientEmails)); emailLogRequest.setRecipientEmails(String.valueOf(recipientEmails));
} }
emailNotificationDao.sendMail(hub.getId(), subject, body, recipientEmails,emailLogRequest); EmailLogEntity emailLog=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body, recipientEmails,emailLog);
} }
private void sendMailTodefaultSystemAndGepafin(UserEntity userEntity, ApplicationEntity applicationEntity) { private void sendMailTodefaultSystemAndGepafin(UserEntity userEntity, ApplicationEntity applicationEntity) {
CallEntity call = applicationEntity.getCall(); CallEntity call = applicationEntity.getCall();
@@ -1316,7 +1322,7 @@ public class ApplicationDao {
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders); String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders); String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId()); EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId(),subject,body);
List<String> hubEmails = Arrays.stream(hub.getEmail().split(",")) List<String> hubEmails = Arrays.stream(hub.getEmail().split(","))
.map(String::trim) .map(String::trim)
@@ -1324,9 +1330,11 @@ public class ApplicationDao {
.toList(); .toList();
emailLogRequest.setRecipientEmails(hub.getEmail()); emailLogRequest.setRecipientEmails(hub.getEmail());
emailNotificationDao.sendMail(hub.getId(), subject, body,hubEmails,emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body,hubEmails,emailLogEntity);
emailLogRequest.setRecipientEmails(rinaldoEmail); emailLogRequest.setRecipientEmails(rinaldoEmail);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(rinaldoEmail),emailLogRequest); EmailLogEntity emailLog=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(rinaldoEmail),emailLog);
} }
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId, public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,
MultipartFile file) { MultipartFile file) {
@@ -1383,7 +1391,7 @@ public class ApplicationDao {
ApplicationSignedDocumentEntity oldApplicationSignedDocument = Utils.getClonedEntityForData(applicationSignedDocumentEntity); ApplicationSignedDocumentEntity oldApplicationSignedDocument = Utils.getClonedEntityForData(applicationSignedDocumentEntity);
String oldS3Path = applicationSignedDocumentEntity.getFilePath(); String oldS3Path = applicationSignedDocumentEntity.getFilePath();
log.debug("Old S3 path: {} ", oldS3Path); log.debug("Old S3 path: {} ", oldS3Path);
String newS3Path = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.DELETED_USER_SIGNED_DOCUMENT,applicationSignedDocumentEntity.getApplication().getCall().getId(),applicationSignedDocumentEntity.getApplication().getId(),0L,0L); String newS3Path = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.DELETED_USER_SIGNED_DOCUMENT,applicationSignedDocumentEntity.getApplication().getCall().getId(),applicationSignedDocumentEntity.getApplication().getId(),0L,0L,0l);
log.debug("Generated new S3 path for deleted document: {}", newS3Path); log.debug("Generated new S3 path for deleted document: {}", newS3Path);
UploadFileOnAmazonS3Response response = amazonS3Service.moveFile(applicationSignedDocumentEntity.getFileName(), oldS3Path, newS3Path); UploadFileOnAmazonS3Response response = amazonS3Service.moveFile(applicationSignedDocumentEntity.getFileName(), oldS3Path, newS3Path);
@@ -1418,7 +1426,7 @@ public class ApplicationDao {
} }
private String generateS3PathForDelegation(Long callId, Long applicationId) { private String generateS3PathForDelegation(Long callId, Long applicationId) {
try { try {
return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId,0L,0L); return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId,0L,0L,0L);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.error("Failed to generate S3 path for delegation | callId: {}, applicationId: {}, error: {}", callId, applicationId, e.getMessage(), e); log.error("Failed to generate S3 path for delegation | callId: {}, applicationId: {}, error: {}", callId, applicationId, e.getMessage(), e);
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG)); throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
@@ -1541,11 +1549,12 @@ public class ApplicationDao {
List<DocumentEntity> amendmentDocuments = fetchAmendmentDocuments(applicationId); List<DocumentEntity> amendmentDocuments = fetchAmendmentDocuments(applicationId);
List<DocumentEntity> evaluationDocuments = fetchEvaluationDocuments(applicationId); List<DocumentEntity> evaluationDocuments = fetchEvaluationDocuments(applicationId);
List<DocumentEntity> communicationnDocuments = fetchCommunicationDocuments(applicationId); List<DocumentEntity> communicationnDocuments = fetchCommunicationDocuments(applicationId);
List<DocumentEntity> contractDocuments=fetchContractDocuments(applicationId);
if (documents.isEmpty() && signedDocument == null && amendmentDocuments.isEmpty() && evaluationDocuments.isEmpty()) { if (documents.isEmpty() && signedDocument == null && amendmentDocuments.isEmpty() && evaluationDocuments.isEmpty()) {
log.warn("No documents found for applicationId: {}", applicationId); log.warn("No documents found for applicationId: {}", applicationId);
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND)); throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
} }
return createZipWithDocuments(applicationEntity, documents, signedDocument, amendmentDocuments, evaluationDocuments, applicationId,communicationnDocuments); return createZipWithDocuments(applicationEntity, documents, signedDocument, amendmentDocuments, evaluationDocuments, applicationId,communicationnDocuments,contractDocuments);
} }
private void validateAssignedUser(HttpServletRequest request, Long applicationId) { private void validateAssignedUser(HttpServletRequest request, Long applicationId) {
@@ -1637,12 +1646,12 @@ public class ApplicationDao {
} }
} }
private byte[] createZipWithDocuments(ApplicationEntity applicationEntity, List<DocumentEntity> documents, ApplicationSignedDocumentEntity signedDocument, private byte[] createZipWithDocuments(ApplicationEntity applicationEntity, List<DocumentEntity> documents, ApplicationSignedDocumentEntity signedDocument,
List<DocumentEntity> amendmentDocuments, List<DocumentEntity> evaluationDocuments, Long applicationId,List<DocumentEntity> communicationDocuments) { List<DocumentEntity> amendmentDocuments, List<DocumentEntity> evaluationDocuments, Long applicationId,List<DocumentEntity> communicationDocuments,List<DocumentEntity> contractDocuments) {
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) { try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
Long callId = applicationEntity.getCall().getId(); Long callId = applicationEntity.getCall().getId();
// Add Application Documents // Add Application Documents
String appS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION, callId, applicationId, 0L,0L); String appS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION, callId, applicationId, 0L,0L,0L);
for (DocumentEntity document : documents) { for (DocumentEntity document : documents) {
String fileName = Utils.extractFileName(document.getFilePath()); String fileName = Utils.extractFileName(document.getFilePath());
addDocumentToZip(zos, appS3Folder, document.getFilePath(), fileName); addDocumentToZip(zos, appS3Folder, document.getFilePath(), fileName);
@@ -1650,7 +1659,7 @@ public class ApplicationDao {
// Add Signed Document // Add Signed Document
if (signedDocument != null) { if (signedDocument != null) {
String signedFolder = "SIGNED_DOCUMENT/"; String signedFolder = "SIGNED_DOCUMENT/";
String signedDocS3Folder = s3PathConfig.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId, 0L,0L); String signedDocS3Folder = s3PathConfig.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId, 0L,0L,0L);
String fileName = signedDocument.getFileName(); String fileName = signedDocument.getFileName();
addDocumentToZip(zos, signedDocS3Folder, signedDocument.getFilePath(), signedFolder + fileName); addDocumentToZip(zos, signedDocS3Folder, signedDocument.getFilePath(), signedFolder + fileName);
} }
@@ -1658,23 +1667,30 @@ public class ApplicationDao {
for (DocumentEntity amendmentDocument : amendmentDocuments) { for (DocumentEntity amendmentDocument : amendmentDocuments) {
String protocolNumber = fetchProtocolNumberForAmendment(amendmentDocument.getSourceId()); String protocolNumber = fetchProtocolNumberForAmendment(amendmentDocument.getSourceId());
String amendmentFolder = "SOCCORSO_" + protocolNumber + "/"; String amendmentFolder = "SOCCORSO_" + protocolNumber + "/";
String amendmentS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.AMENDMENT, callId, applicationId, amendmentDocument.getSourceId(),0L); String amendmentS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.AMENDMENT, callId, applicationId, amendmentDocument.getSourceId(),0L,0L);
String fileName = Utils.extractFileName(amendmentDocument.getFilePath()); String fileName = Utils.extractFileName(amendmentDocument.getFilePath());
addDocumentToZip(zos, amendmentS3Folder, amendmentDocument.getFilePath(), amendmentFolder + fileName); addDocumentToZip(zos, amendmentS3Folder, amendmentDocument.getFilePath(), amendmentFolder + fileName);
} }
// Add Evaluation Documents // Add Evaluation Documents
for (DocumentEntity evaluationDocument : evaluationDocuments) { for (DocumentEntity evaluationDocument : evaluationDocuments) {
String evaluationFolder = "EVALUATION/"; String evaluationFolder = "EVALUATION/";
String evaluationS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.EVALUATION, callId, applicationId, evaluationDocument.getSourceId(),0L); String evaluationS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.EVALUATION, callId, applicationId, evaluationDocument.getSourceId(),0L,0L);
String fileName = Utils.extractFileName(evaluationDocument.getFilePath()); String fileName = Utils.extractFileName(evaluationDocument.getFilePath());
addDocumentToZip(zos, evaluationS3Folder, evaluationDocument.getFilePath(), evaluationFolder + fileName); addDocumentToZip(zos, evaluationS3Folder, evaluationDocument.getFilePath(), evaluationFolder + fileName);
} }
for (DocumentEntity communicationDocument : communicationDocuments) { for (DocumentEntity communicationDocument : communicationDocuments) {
Optional<CommunicationEntity> communicationEntity=communicationRepository.findByIdAndIsDeletedFalse(communicationDocument.getSourceId()); Optional<CommunicationEntity> communicationEntity=communicationRepository.findByIdAndIsDeletedFalse(communicationDocument.getSourceId());
String evaluationFolder = "COMMUNICATION/"; String communicationFolder = "COMMUNICATION/";
String evaluationS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.COMMUNICATION, callId, applicationId, communicationEntity.get().getApplicationAmendmentRequest().getId(),communicationDocument.getSourceId()); String communicationS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.COMMUNICATION, callId, applicationId, communicationEntity.get().getApplicationAmendmentRequest().getId(),communicationDocument.getSourceId(),0L);
String fileName = Utils.extractFileName(communicationDocument.getFilePath()); String fileName = Utils.extractFileName(communicationDocument.getFilePath());
addDocumentToZip(zos, evaluationS3Folder, communicationDocument.getFilePath(), evaluationFolder + fileName); addDocumentToZip(zos, communicationS3Folder, communicationDocument.getFilePath(), communicationFolder + fileName);
}
for (DocumentEntity contractDocument : contractDocuments) {
ApplicationContractEntity applicationContractEntity=applicationContractRepository.findByIdAndIsDeletedFalse(contractDocument.getSourceId());
String contractFolder = "CONTRACT/";
String contractS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.CONTRACT, callId, applicationId, 0L,0L,applicationContractEntity.getId());
String fileName = Utils.extractFileName(contractDocument.getFilePath());
addDocumentToZip(zos, contractS3Folder, contractDocument.getFilePath(), contractFolder + fileName);
} }
zos.finish(); zos.finish();
return zipOutputStream.toByteArray(); return zipOutputStream.toByteArray();
@@ -1849,7 +1865,6 @@ public class ApplicationDao {
if (expression.matches(".*\\{.*\\}.*")) { if (expression.matches(".*\\{.*\\}.*")) {
return 0; return 0;
} }
// Step 4: Evaluate the mathematical expression // Step 4: Evaluate the mathematical expression
return Utils.evaluateExpression(expression); return Utils.evaluateExpression(expression);
} }
@@ -2437,14 +2452,14 @@ public class ApplicationDao {
} }
public void sendApplicationSubmissionFailureEmail(EmailLogRequest emailLogRequest){ public void sendApplicationSubmissionFailureEmail(EmailLogEntity emailLogEntity){
Long callId = emailLogRequest.getCallId(); Long callId = emailLogEntity.getCallId();
CallEntity call = callService.validateCall(callId); CallEntity call = callService.validateCall(callId);
HubEntity hub = call.getHub(); HubEntity hub = call.getHub();
Long userId = emailLogRequest.getUserId(); Long userId = emailLogEntity.getUserId();
UserEntity user = userService.validateUser(userId); UserEntity user = userService.validateUser(userId);
Long applicationId = emailLogRequest.getApplicatioId(); Long applicationId = emailLogEntity.getApplicationId();
ApplicationEntity applicationEntity = validateApplication(applicationId); ApplicationEntity applicationEntity = validateApplication(applicationId);
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId()); CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
@@ -2457,7 +2472,7 @@ public class ApplicationDao {
subjectPlaceholders.put("{{call_name}}", call.getName()); subjectPlaceholders.put("{{call_name}}", call.getName());
Map<String, String> bodyPlaceholders = new HashMap<>(); Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{scenario}}",emailLogRequest.getEmailType().getValue()); bodyPlaceholders.put("{{scenario}}",emailLogEntity.getEmailType());
bodyPlaceholders.put("{{call_name}}", call.getName()); bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{application_id}}", applicationEntity.getId().toString()); bodyPlaceholders.put("{{application_id}}", applicationEntity.getId().toString());
bodyPlaceholders.put("{{company_name}}", company.getCompanyName()); bodyPlaceholders.put("{{company_name}}", company.getCompanyName());
@@ -2466,15 +2481,16 @@ public class ApplicationDao {
protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber()); protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
} }
bodyPlaceholders.put("{{protocol_number}}", protocolNumber); bodyPlaceholders.put("{{protocol_number}}", protocolNumber);
bodyPlaceholders.put("{{user_action_id}}",emailLogRequest.getUserActionId().toString()); bodyPlaceholders.put("{{user_action_id}}",emailLogEntity.getUserAction().getId().toString());
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders); String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders); String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,user.getEmail(),user.getId(),applicationEntity.getId(),null,callId); EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,user.getEmail(),user.getId(),applicationEntity.getId(),null,callId,subject,body);
emailLogRequest.setRecipientEmails(GepafinConstant.RINALDO_EMAIL); emailLogRequest.setRecipientEmails(GepafinConstant.RINALDO_EMAIL);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(GepafinConstant.RINALDO_EMAIL),emailLogRequest); EmailLogEntity newEmailLogEntity=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(GepafinConstant.RINALDO_EMAIL),newEmailLogEntity);
} }
public byte[] downloadRankingCsv(Long callId,UserEntity userEntity) { public byte[] downloadRankingCsv(Long callId,UserEntity userEntity) {
@@ -2600,5 +2616,18 @@ public class ApplicationDao {
return out.toByteArray(); return out.toByteArray();
} }
private List<DocumentEntity> fetchContractDocuments(Long applicationId) {
log.info("Fetching contract documents for applicationId: {}", applicationId);
ApplicationContractEntity applicationContractEntity=applicationContractRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
List<DocumentEntity> documentEntities=new ArrayList<>();
if(applicationContractEntity!=null){
Long contractId = applicationContractEntity.getId();
log.debug("Found contract entity with id: {}", contractId);
List<DocumentEntity> communicationDocuments= documentRepository.findBySourceIdInAndSourceAndIsDeletedFalse(Collections.singleton(contractId), DocumentSourceTypeEnum.CONTRACT.getValue());
documentEntities.addAll(communicationDocuments);
return documentEntities;
}
return Collections.emptyList();
}
} }

View File

@@ -157,6 +157,9 @@ public class ApplicationEvaluationDao {
@Autowired @Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository; private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
@Autowired
private ApplicationContractDao applicationContractDao;
private ApplicationEvaluationEntity convertToEntity(UserEntity user, ApplicationEvaluationRequest req, Long assignedApplciationId) { private ApplicationEvaluationEntity convertToEntity(UserEntity user, ApplicationEvaluationRequest req, Long assignedApplciationId) {
ApplicationEvaluationEntity entity = new ApplicationEvaluationEntity(); ApplicationEvaluationEntity entity = new ApplicationEvaluationEntity();
@@ -651,8 +654,8 @@ public class ApplicationEvaluationDao {
CallEntity call = callRepository.findCallEntityByApplicationId(entity.getApplicationId()); CallEntity call = callRepository.findCallEntityByApplicationId(entity.getApplicationId());
String firstName = user.getBeneficiary().getFirstName() != null ? user.getBeneficiary().getFirstName() : ""; String firstName = user.getBeneficiary() != null ? user.getBeneficiary().getFirstName() : "";
String lastName = user.getBeneficiary().getLastName() != null ? user.getBeneficiary().getLastName() : ""; String lastName = user.getBeneficiary() != null ? user.getBeneficiary().getLastName() : "";
String beneficiary = String.join(" ", firstName, lastName).trim(); String beneficiary = String.join(" ", firstName, lastName).trim();
response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(application.getStatus())); response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(application.getStatus()));
response.setBeneficiary(beneficiary); response.setBeneficiary(beneficiary);
@@ -1193,6 +1196,8 @@ public class ApplicationEvaluationDao {
ApplicationEvaluationResponse applicationEvaluationResponse = convertToResponse(entity); ApplicationEvaluationResponse applicationEvaluationResponse = convertToResponse(entity);
applicationEvaluationResponse.setSignedDocument(getApplicationSignedDocument(entity)); applicationEvaluationResponse.setSignedDocument(getApplicationSignedDocument(entity));
applicationEvaluationResponse.setEmailSendResponse(entity.getEmailSendResponse()); applicationEvaluationResponse.setEmailSendResponse(entity.getEmailSendResponse());
ApplicationContractResponse applicationContractResponse=applicationContractDao.getContractByApplicationId(applicationID);
applicationEvaluationResponse.setContract(applicationContractResponse);
return applicationEvaluationResponse; return applicationEvaluationResponse;
} }
public List<EvaluationDocumentRequest> prepareEvaluationDocumentBeanList(ApplicationEvaluationEntity entity) { public List<EvaluationDocumentRequest> prepareEvaluationDocumentBeanList(ApplicationEvaluationEntity entity) {
@@ -2423,6 +2428,8 @@ public class ApplicationEvaluationDao {
response.setCompanyCodiceAteco(company.getCodiceAteco()); response.setCompanyCodiceAteco(company.getCodiceAteco());
response.setSignedDocument(getApplicationSignedDocument(evaluationEntity)); response.setSignedDocument(getApplicationSignedDocument(evaluationEntity));
response.setEmailSendResponse(evaluationEntity.getEmailSendResponse()); response.setEmailSendResponse(evaluationEntity.getEmailSendResponse());
ApplicationContractResponse applicationContractResponse=applicationContractDao.getContractByApplicationId(evaluationEntity.getApplicationId());
response.setContract(applicationContractResponse);
return response; return response;
} }

View File

@@ -553,9 +553,13 @@ public class AppointmentDao {
String authorizationToken = getBearerToken(hub); String authorizationToken = getBearerToken(hub);
// Try retrieving NDG by VAT number // Try retrieving NDG by VAT number
NdganagEntity ndganagEntity = ndganagRepository.findByVatNumber(company.getVatNumber());
AppointmentLoginResponse ndgResponse=new AppointmentLoginResponse(); AppointmentLoginResponse ndgResponse=new AppointmentLoginResponse();
ndgResponse = retrieveNdgByVatNumber(company.getVatNumber(), authorizationToken, hub, application); if (ndganagEntity != null && ndganagEntity.getNdg() != null) {
ndgResponse.setNdg(ndganagEntity.getNdg());
}else {
ndgResponse = retrieveNdgByVatNumber(company.getVatNumber(), authorizationToken, hub, application,company);
}
if (isNdgValid(ndgResponse.getNdg())) { if (isNdgValid(ndgResponse.getNdg())) {
saveNdg(application, company, ndgResponse.getNdg()); saveNdg(application, company, ndgResponse.getNdg());
log.info("NDG successfully generated for applicationId: {}", applicationId); log.info("NDG successfully generated for applicationId: {}", applicationId);
@@ -731,20 +735,38 @@ public class AppointmentDao {
} }
} }
private AppointmentLoginResponse retrieveNdgByVatNumber(String vatNumber, String authorizationToken, HubEntity hub, ApplicationEntity application) { private AppointmentLoginResponse retrieveNdgByVatNumber(String vatNumber, String authorizationToken, HubEntity hub, ApplicationEntity application,CompanyEntity company) {
try { try {
log.info("Initiating NDG retrieval by VAT number | ApplicationId: {}, HubId: {}, VAT: {}", application.getId(), hub.getId(), vatNumber); log.info("Initiating NDG retrieval by VAT number | ApplicationId: {}, HubId: {}, VAT: {}", application.getId(), hub.getId(), vatNumber);
// Prepare the NDG request // Prepare the NDG request
String responseJson = getNdgFromExternalService(vatNumber, authorizationToken); String responseJson = getNdgFromExternalService(vatNumber, authorizationToken);
// Parse and return the NDG response // Parse and return the NDG response
return parseNdgResponse(responseJson); AppointmentLoginResponse loginResponse=parseNdgResponse(responseJson);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = null;
try {
rootNode = objectMapper.readTree(responseJson);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
JsonNode dataArray = rootNode.get(GepafinConstant.DATA_STRING);
JsonNode firstDataEntry = dataArray.get(0);
NdganagEntity ndganagEntity=new NdganagEntity();
ndganagEntity.setNdg(loginResponse.getNdg());
ndganagEntity.setVatNumber(loginResponse.getVatNumber());
ndganagEntity.setCodiceFiscale(loginResponse.getCodecFiscale());
ndganagEntity.setJson(firstDataEntry.toString());
ndganagEntity.setIsDeleted(Boolean.FALSE);
ndganagEntity.setCompanyName(company.getCompanyName());
ndganagRepository.save(ndganagEntity);
return loginResponse;
} catch (FeignException.Forbidden forbiddenException) { } catch (FeignException.Forbidden forbiddenException) {
log.error("403 Forbidden during NDG retrieval | ApplicationId: {}, HubId: {}", application.getId(), hub.getId()); log.error("403 Forbidden during NDG retrieval | ApplicationId: {}, HubId: {}", application.getId(), hub.getId());
logForbiddenError(); logForbiddenError();
// Regenerate the token and retry // Regenerate the token and retry
String newAuthorizationToken = regenerateTokenAndSave(hub, application); String newAuthorizationToken = regenerateTokenAndSave(hub, application);
return retrieveNdgByVatNumber(vatNumber, newAuthorizationToken, hub, application); return retrieveNdgByVatNumber(vatNumber, newAuthorizationToken, hub, application,company);
} catch (Exception e) { } catch (Exception e) {
log.error("Error during NDG retrieval | ApplicationId: {}, HubId: {}, Message: {}", application.getId(), hub.getId(), e.getMessage(), e); log.error("Error during NDG retrieval | ApplicationId: {}, HubId: {}, Message: {}", application.getId(), hub.getId(), e.getMessage(), e);
throw new RuntimeException("NDG retrieval failed.", e); throw new RuntimeException("NDG retrieval failed.", e);
@@ -894,6 +916,7 @@ public class AppointmentDao {
public AppointmentLoginResponse parseNdgResponse(String jsonResponse) { public AppointmentLoginResponse parseNdgResponse(String jsonResponse) {
AppointmentLoginResponse loginResponse = new AppointmentLoginResponse(); AppointmentLoginResponse loginResponse = new AppointmentLoginResponse();
String ndg=extractNdg(jsonResponse); String ndg=extractNdg(jsonResponse);
if (ndg==null){ return null;} if (ndg==null){ return null;}
else { else {
loginResponse.setNdg(ndg); loginResponse.setNdg(ndg);
@@ -1510,7 +1533,7 @@ public class AppointmentDao {
log.info("Initiating NDG retrieval by VAT number | HubId: {}, VAT: {}", hub.getId(), vatNumber); log.info("Initiating NDG retrieval by VAT number | HubId: {}, VAT: {}", hub.getId(), vatNumber);
// Prepare the NDG request // Prepare the NDG request
jsonResponse=getNdgFromExternalService(vatNumber, authorizationToken); jsonResponse=getNdgFromExternalService(vatNumber, authorizationToken);
checkAndSaveNdg(jsonResponse, ndgResponse); checkAndSaveNdg(jsonResponse, ndgResponse,vatNumber);
// Parse and return the NDG response // Parse and return the NDG response
} catch (FeignException.Forbidden forbiddenException) { } catch (FeignException.Forbidden forbiddenException) {
log.error("403 Forbidden during NDG retrieval | HubId: {}", hub.getId()); log.error("403 Forbidden during NDG retrieval | HubId: {}", hub.getId());
@@ -1518,7 +1541,7 @@ public class AppointmentDao {
// Regenerate the token and retry // Regenerate the token and retry
String newAuthorizationToken = regenerateTokenAndSave(hub, null); String newAuthorizationToken = regenerateTokenAndSave(hub, null);
jsonResponse= getNdgFromExternalService(vatNumber,newAuthorizationToken); jsonResponse= getNdgFromExternalService(vatNumber,newAuthorizationToken);
if (checkAndSaveNdg(jsonResponse, ndgResponse)) return null; if (checkAndSaveNdg(jsonResponse, ndgResponse,vatNumber)) return null;
} catch (Exception e) { } catch (Exception e) {
log.error("Error during NDG retrieval |, HubId: {}, Message: {}", hub.getId(), e.getMessage(), e); log.error("Error during NDG retrieval |, HubId: {}, Message: {}", hub.getId(), e.getMessage(), e);
throw new RuntimeException("NDG retrieval failed.", e); throw new RuntimeException("NDG retrieval failed.", e);
@@ -1529,8 +1552,25 @@ public class AppointmentDao {
return ndgResponse; return ndgResponse;
} }
private boolean checkAndSaveNdg(String jsonResponse, NdgResponse ndgResponse) { private boolean checkAndSaveNdg(String jsonResponse, NdgResponse ndgResponse,String vatNumber) {
String ndg=extractNdg(jsonResponse); String ndg=extractNdg(jsonResponse);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = null;
try {
rootNode = objectMapper.readTree(jsonResponse);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
JsonNode dataArray = rootNode.get(GepafinConstant.DATA_STRING);
JsonNode firstDataEntry = dataArray.get(0);
String comapnyName=normalizeNullValue(firstDataEntry.get(GepafinConstant.COMPANY_NAME_JSON).asText());
NdganagEntity ndganagEntity=new NdganagEntity();
ndganagEntity.setNdg(ndg);
ndganagEntity.setVatNumber(vatNumber);
ndganagEntity.setJson(firstDataEntry.toString());
ndganagEntity.setIsDeleted(Boolean.FALSE);
ndganagEntity.setCompanyName(comapnyName);
ndganagRepository.save(ndganagEntity);
if (ndg==null){ if (ndg==null){
return true; return true;
} }

View File

@@ -14,6 +14,7 @@ import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest; import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest; import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest; import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
import net.gepafin.tendermanagement.model.response.ApplicationContractResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationViewResponse; import net.gepafin.tendermanagement.model.response.AssignedApplicationViewResponse;
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse; import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
import net.gepafin.tendermanagement.model.response.PageableResponseBean; import net.gepafin.tendermanagement.model.response.PageableResponseBean;
@@ -82,6 +83,9 @@ public class AssignedApplicationsDao {
@Autowired @Autowired
private AssignedApplicationsViewRepository assignedApplicationsViewRepository; private AssignedApplicationsViewRepository assignedApplicationsViewRepository;
@Autowired
private ApplicationContractDao applicationContractDao;
public AssignedApplicationsResponse createAssignedApplications(Long applicationId, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest) { public AssignedApplicationsResponse createAssignedApplications(Long applicationId, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest) {
log.info("Assigning application to pre-Instructor with details: {}", applicationId, userId); log.info("Assigning application to pre-Instructor with details: {}", applicationId, userId);
@@ -492,6 +496,8 @@ public class AssignedApplicationsDao {
response.setUpdatedDate(view.getUpdatedDate()); response.setUpdatedDate(view.getUpdatedDate());
response.setEmailSendResponse(view.getEmailSendResponse()); response.setEmailSendResponse(view.getEmailSendResponse());
response.setAssignedUserName(view.getAssignedUserName()); response.setAssignedUserName(view.getAssignedUserName());
ApplicationContractResponse applicationContractResponse=applicationContractDao.getContractByApplicationId(response.getApplicationId());
response.setContract(applicationContractResponse);
return response; return response;
} }

View File

@@ -155,7 +155,7 @@ public class CallDao {
for (DocumentEntity document : documents) { for (DocumentEntity document : documents) {
log.info("Adding document to ZIP: documentId={}, fileName={}", document.getId(), document.getFileName()); log.info("Adding document to ZIP: documentId={}, fileName={}", document.getId(), document.getFileName());
String s3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.CALL, callId, 0L,0L,0L); String s3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.CALL, callId, 0L,0L,0L,0L);
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFilePath())) { try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFilePath())) {
String fileName = Utils.extractFileName(document.getFilePath()); String fileName = Utils.extractFileName(document.getFilePath());
ZipEntry zipEntry = new ZipEntry(fileName); ZipEntry zipEntry = new ZipEntry(fileName);

View File

@@ -281,7 +281,7 @@ public class CompanyDocumentDao {
validator.validateUserWithCompany(request,companyDocumentEntity.getCompanyId()); validator.validateUserWithCompany(request,companyDocumentEntity.getCompanyId());
String companyDocumentPath = companyDocumentEntity.getFilePath(); String companyDocumentPath = companyDocumentEntity.getFilePath();
String documentPath = s3ConfigBean.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION,applicationEntity.getCall().getId(),applicationId,0L,0L); String documentPath = s3ConfigBean.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION,applicationEntity.getCall().getId(),applicationId,0L,0L,0L);
log.info("Original Paths - oldPath: {}, newPath: {}", companyDocumentPath, documentPath); log.info("Original Paths - oldPath: {}, newPath: {}", companyDocumentPath, documentPath);

View File

@@ -92,7 +92,7 @@ public class DelegationDao {
public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) { public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) {
try { try {
String s3Folder = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.TEMPLATE, 0L, 0L,0L,0L); String s3Folder = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.TEMPLATE, 0L, 0L,0L,0L,0L);
InputStream templateStream = amazonS3Service.getFile(s3Folder ,templateName); InputStream templateStream = amazonS3Service.getFile(s3Folder ,templateName);
XWPFDocument doc = loadTemplate(templateStream); XWPFDocument doc = loadTemplate(templateStream);
replacePlaceholders(doc, placeholders); replacePlaceholders(doc, placeholders);

View File

@@ -93,6 +93,9 @@ public class DocumentDao {
@Autowired @Autowired
private CommunicationRepository communicationRepository; private CommunicationRepository communicationRepository;
@Autowired
private ApplicationContractRepository applicationContractRepository;
// @Value("${aws.s3.url.folder}") // @Value("${aws.s3.url.folder}")
// private String s3Folder; // private String s3Folder;
@@ -172,6 +175,7 @@ public class DocumentDao {
Long amendmentId = 0L; Long amendmentId = 0L;
Long evaluationId = 0L; Long evaluationId = 0L;
Long communicationId = 0L; Long communicationId = 0L;
Long contractId=0L;
Long callId = sourceId; Long callId = sourceId;
if (type == DocumentSourceTypeEnum.APPLICATION) { if (type == DocumentSourceTypeEnum.APPLICATION) {
applicationId = sourceId; applicationId = sourceId;
@@ -197,9 +201,16 @@ public class DocumentDao {
applicationId=applicationAmendmentRequestEntity.get().getApplicationId(); applicationId=applicationAmendmentRequestEntity.get().getApplicationId();
callId = applicationAmendmentRequestEntity.get().getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getCall().getId(); callId = applicationAmendmentRequestEntity.get().getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getCall().getId();
log.info("Processing document of type COMMUNICATION .Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId); log.info("Processing document of type COMMUNICATION .Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId);
}else if (type == DocumentSourceTypeEnum.CONTRACT) {
contractId = sourceId;
ApplicationContractEntity applicationContractEntity=applicationContractRepository.findByIdAndIsDeletedFalse(contractId);
ApplicationEntity applicationEntity=applicationService.validateApplication(applicationContractEntity.getApplicationId());
applicationId=applicationEntity.getId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type CONTRACT .Resolved evaluationId={}, applicationId={}, callId={}, contractId={}", evaluationId, applicationId, callId,contractId);
} }
try { try {
String s3Path = generateS3Path(type, callId, applicationId, amendmentId,communicationId); String s3Path = generateS3Path(type, callId, applicationId, amendmentId,communicationId,contractId);
log.info("Generated S3 path {}", s3Path); log.info("Generated S3 path {}", s3Path);
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file); return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
} catch (Exception e) { } catch (Exception e) {
@@ -210,9 +221,9 @@ public class DocumentDao {
} }
public String generateS3Path(DocumentSourceTypeEnum typeOfDocument, Long callId, Long applicationId, Long amendmentId,Long communicationId) { public String generateS3Path(DocumentSourceTypeEnum typeOfDocument, Long callId, Long applicationId, Long amendmentId,Long communicationId,Long contractId) {
try { try {
return s3ConfigBean.generateDocumentPath(typeOfDocument, callId, applicationId, amendmentId,communicationId); return s3ConfigBean.generateDocumentPath(typeOfDocument, callId, applicationId, amendmentId,communicationId,contractId);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG)); throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
} }
@@ -245,6 +256,7 @@ public class DocumentDao {
Long amendmentId = null; Long amendmentId = null;
Long evaluationId = null; Long evaluationId = null;
Long communicationId=null; Long communicationId=null;
Long contractId=null;
if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(documentEntity.getSource())) { if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(documentEntity.getSource())) {
callId = documentEntity.getSourceId(); callId = documentEntity.getSourceId();
@@ -340,9 +352,20 @@ public class DocumentDao {
communicationEntity1.setDocuments(updatedValue); communicationEntity1.setDocuments(updatedValue);
communicationRepository.save(communicationEntity1); communicationRepository.save(communicationEntity1);
} }
}
else if(DocumentSourceTypeEnum.CONTRACT.getValue().equalsIgnoreCase(documentEntity.getSource())) {
contractId = documentEntity.getSourceId();
ApplicationContractEntity applicationContractEntity=applicationContractRepository.findByIdAndIsDeletedFalse(contractId);
ApplicationEntity applicationEntity=applicationService.validateApplication(applicationContractEntity.getApplicationId());
String beneficiaryDocument=applicationContractEntity.getBeneficiaryDocument();
if(beneficiaryDocument!=null) {
String updatedValue = removeDocumentIdFromFieldValue(beneficiaryDocument, documentId);
applicationContractEntity.setBeneficiaryDocument(updatedValue);
applicationContractRepository.save(applicationContractEntity);
}
} }
deleteFileFromS3(documentEntity, callId, applicationId,amendmentId,communicationId); deleteFileFromS3(documentEntity, callId, applicationId,amendmentId,communicationId,contractId);
log.info("Successfully deleted file from S3 for documentId={}", documentId); log.info("Successfully deleted file from S3 for documentId={}", documentId);
} }
@@ -387,6 +410,7 @@ public class DocumentDao {
Long amendmentId=null; Long amendmentId=null;
Long evaluationId=null; Long evaluationId=null;
Long communicationId=null; Long communicationId=null;
Long contractId=null;
if (type.equals(DocumentSourceTypeEnum.APPLICATION)) { if (type.equals(DocumentSourceTypeEnum.APPLICATION)) {
callId = applicationRepository.findCallIdById(id); callId = applicationRepository.findCallIdById(id);
applicationId = id; applicationId = id;
@@ -412,6 +436,13 @@ public class DocumentDao {
applicationId=applicationAmendmentRequestEntity.get().getApplicationId(); applicationId=applicationAmendmentRequestEntity.get().getApplicationId();
callId = applicationAmendmentRequestEntity.get().getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getCall().getId(); callId = applicationAmendmentRequestEntity.get().getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().getCall().getId();
log.info("Processing document of type EVALUATION .Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId); log.info("Processing document of type EVALUATION .Resolved evaluationId={}, applicationId={}, callId={}", evaluationId, applicationId, callId);
}else if (type == DocumentSourceTypeEnum.CONTRACT) {
contractId = id;
ApplicationContractEntity applicationContractEntity=applicationContractRepository.findByIdAndIsDeletedFalse(contractId);
ApplicationEntity applicationEntity=applicationService.validateApplication(applicationContractEntity.getApplicationId());
applicationId=applicationContractEntity.getApplicationId();
callId = applicationEntity.getCall().getId();
log.info("Processing document of type CONTRACT .Resolved evaluationId={}, applicationId={}, callId={}, contractId={}", evaluationId, applicationId, callId,contractId);
} }
else { else {
@@ -419,7 +450,7 @@ public class DocumentDao {
applicationId = 0L; applicationId = 0L;
log.info("Processing document of type CALL . Resolved callId={}", callId); log.info("Processing document of type CALL . Resolved callId={}", callId);
} }
String s3Path = generateS3Path(type, callId, applicationId,amendmentId,communicationId); String s3Path = generateS3Path(type, callId, applicationId,amendmentId,communicationId,contractId);
log.info("Generated S3 path {}", s3Path); log.info("Generated S3 path {}", s3Path);
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file); return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
} catch (Exception e) { } catch (Exception e) {
@@ -432,12 +463,12 @@ public class DocumentDao {
return callDao.convertToDocumentResponseBean(documentEntity); return callDao.convertToDocumentResponseBean(documentEntity);
} }
public void deleteFileFromS3(DocumentEntity documentEntity, Long callId, Long applicationId,Long amendmentId,Long communicationId) { public void deleteFileFromS3(DocumentEntity documentEntity, Long callId, Long applicationId,Long amendmentId,Long communicationId,Long contractId) {
try { try {
DocumentEntity oldDocumentEntity = Utils.getClonedEntityForData(documentEntity); DocumentEntity oldDocumentEntity = Utils.getClonedEntityForData(documentEntity);
String oldS3Path = documentEntity.getFilePath(); String oldS3Path = documentEntity.getFilePath();
String newS3Path = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.valueOf("DELETED_" + documentEntity.getSource().toUpperCase()), callId, applicationId,amendmentId,communicationId); String newS3Path = s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.valueOf("DELETED_" + documentEntity.getSource().toUpperCase()), callId, applicationId,amendmentId,communicationId,contractId);
log.info("Moving file to deleted path: oldS3Path={}, newS3Path={}", oldS3Path, newS3Path); log.info("Moving file to deleted path: oldS3Path={}, newS3Path={}", oldS3Path, newS3Path);
UploadFileOnAmazonS3Response response = amazonS3Service.moveFile(documentEntity.getFileName(), oldS3Path, newS3Path); UploadFileOnAmazonS3Response response = amazonS3Service.moveFile(documentEntity.getFileName(), oldS3Path, newS3Path);
documentEntity.setFileName(response.getFileName()); documentEntity.setFileName(response.getFileName());

View File

@@ -73,8 +73,9 @@ public class EmailDao {
log.getUserId(), log.getUserId(),
log.getApplicationId(), log.getApplicationId(),
log.getAmendmentId(), log.getAmendmentId(),
log.getCallId() log.getCallId(),log.getEmailSubject(),log.getEmailBody()
); );
EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,Utils.convertJsonStringToList(log.getAttachments(),String.class));
List<String> recipients = Utils.commaSeparatedStringToList(log.getRecipientEmails()); List<String> recipients = Utils.commaSeparatedStringToList(log.getRecipientEmails());
CallEntity call = callService.validateCall(log.getCallId()); CallEntity call = callService.validateCall(log.getCallId());
@@ -83,7 +84,7 @@ public class EmailDao {
log.getEmailSubject(), log.getEmailSubject(),
log.getEmailBody(), log.getEmailBody(),
recipients, recipients,
emailLogRequest emailLogEntity
); );
} }
EmailSendResponse emailSendResponse = buildEmailSendResponseFromRequest(request); EmailSendResponse emailSendResponse = buildEmailSendResponseFromRequest(request);

View File

@@ -3,20 +3,19 @@ package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.EmailLogEntity; import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum; import net.gepafin.tendermanagement.enums.*;
import net.gepafin.tendermanagement.enums.EmailEntityTypeEnum;
import net.gepafin.tendermanagement.enums.RecipientTypeEnum;
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailLogRequest; import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest; import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
import net.gepafin.tendermanagement.repositories.EmailLogRepository; import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.repositories.UserActionsRepository; import net.gepafin.tendermanagement.repositories.UserActionsRepository;
import net.gepafin.tendermanagement.util.DateTimeUtil; import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.LoggingUtil; import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.util.Utils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List;
@Component @Component
public class EmailLogDao { public class EmailLogDao {
@@ -31,7 +30,7 @@ public class EmailLogDao {
private LoggingUtil loggingUtil; private LoggingUtil loggingUtil;
public EmailLogEntity createEmailLog(EmailLogRequest emailLogRequest) { public EmailLogEntity createEmailLog(EmailLogRequest emailLogRequest,List<String> attachments) {
EmailLogEntity emailLogEntity = new EmailLogEntity(); EmailLogEntity emailLogEntity = new EmailLogEntity();
emailLogEntity.setEmailType(emailLogRequest.getEmailType().getValue()); emailLogEntity.setEmailType(emailLogRequest.getEmailType().getValue());
@@ -40,17 +39,17 @@ public class EmailLogDao {
emailLogEntity.setEmailSubject(emailLogRequest.getEmailSubject()); emailLogEntity.setEmailSubject(emailLogRequest.getEmailSubject());
emailLogEntity.setEmailBody(emailLogRequest.getEmailBody()); emailLogEntity.setEmailBody(emailLogRequest.getEmailBody());
emailLogEntity.setSendStatus(emailLogRequest.getSendStatus()); emailLogEntity.setSendStatus(emailLogRequest.getSendStatus());
emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now())); // Set to now if null
emailLogEntity.setErrorMessage(emailLogRequest.getErrorMessage()); emailLogEntity.setErrorMessage(emailLogRequest.getErrorMessage());
emailLogEntity.setUserId(emailLogRequest.getUserId()); emailLogEntity.setUserId(emailLogRequest.getUserId());
emailLogEntity.setEmailServiceResponse(emailLogRequest.getEmailServiceResponse()); emailLogEntity.setEmailServiceResponse(emailLogRequest.getEmailServiceResponse());
emailLogEntity.setRecipientEmails(emailLogRequest.getRecipientEmails()); emailLogEntity.setRecipientEmails(emailLogRequest.getRecipientEmails());
emailLogEntity.setEmailServiceType(emailLogRequest.getEmailServiceType().getValue());
emailLogEntity.setIsDeleted(false); emailLogEntity.setIsDeleted(false);
emailLogEntity.setApplicationId(emailLogRequest.getApplicatioId()); emailLogEntity.setApplicationId(emailLogRequest.getApplicatioId());
emailLogEntity.setAmendmentId(emailLogRequest.getAmendmentId()); emailLogEntity.setAmendmentId(emailLogRequest.getAmendmentId());
emailLogEntity.setCallId(emailLogRequest.getCallId()); emailLogEntity.setCallId(emailLogRequest.getCallId());
emailLogEntity.setUserAction(loggingUtil.getUserActionLogById(emailLogRequest.getUserActionId())); emailLogEntity.setUserAction(loggingUtil.getUserActionLogById(emailLogRequest.getUserActionId()));
emailLogEntity.setSendStatus(StatusTypeEnum.PENDING.getValue());
emailLogEntity.setAttachments(Utils.convertListToJsonString(attachments));
emailLogEntity = saveEmailLogEntity(emailLogEntity); emailLogEntity = saveEmailLogEntity(emailLogEntity);
return emailLogEntity; return emailLogEntity;
} }
@@ -58,7 +57,7 @@ public class EmailLogDao {
return emailLogRepository.save(emailLogEntity); return emailLogRepository.save(emailLogEntity);
} }
public EmailLogRequest createEmailLogRequest(EmailScenarioTypeEnum emailType, RecipientTypeEnum recipientType, Long recipientId, public EmailLogRequest createEmailLogRequest(EmailScenarioTypeEnum emailType, RecipientTypeEnum recipientType, Long recipientId,
String recipientEmails, Long userId,Long applicationId,Long amendmentId,Long callId) { String recipientEmails, Long userId, Long applicationId, Long amendmentId, Long callId, String subject, String body) {
EmailLogRequest emailLogRequest = new EmailLogRequest(); EmailLogRequest emailLogRequest = new EmailLogRequest();
Long userActionId =(Long) request.getAttribute(GepafinConstant.USER_ACTION_ID); Long userActionId =(Long) request.getAttribute(GepafinConstant.USER_ACTION_ID);
emailLogRequest.setEmailType(emailType); emailLogRequest.setEmailType(emailType);
@@ -70,6 +69,8 @@ public class EmailLogDao {
emailLogRequest.setAmendmentId(amendmentId); emailLogRequest.setAmendmentId(amendmentId);
emailLogRequest.setCallId(callId); emailLogRequest.setCallId(callId);
emailLogRequest.setUserActionId(userActionId); emailLogRequest.setUserActionId(userActionId);
emailLogRequest.setEmailSubject(subject);
emailLogRequest.setEmailBody(body);
return emailLogRequest; return emailLogRequest;
} }
} }

View File

@@ -97,6 +97,9 @@ public class EmailNotificationDao {
@Autowired @Autowired
private ApplicationDao applicationDao; private ApplicationDao applicationDao;
@Autowired
private ApplicationContractDao applicationContractDao;
public void sendEmail(ApplicationEntity applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum templateType, Map<String, String> bodyPlaceholders, public void sendEmail(ApplicationEntity applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum templateType, Map<String, String> bodyPlaceholders,
List<String> additionalRecipients, Long amendmentId,String emailType) { List<String> additionalRecipients, Long amendmentId,String emailType) {
@@ -106,7 +109,7 @@ public class EmailNotificationDao {
EmailContentResponse emailContent = prepareEmailContent(applicationEntity, templateType, hubEntity, bodyPlaceholders,emailType); EmailContentResponse emailContent = prepareEmailContent(applicationEntity, templateType, hubEntity, bodyPlaceholders,emailType);
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId()); UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
sendEmails(applicationEntity, userEntity, additionalRecipients,amendmentId,emailContent.getSystemEmailTemplateResponse(),emailContent.getSubject(),emailContent.getBody()); sendEmails(applicationEntity, userEntity, additionalRecipients,amendmentId,emailContent.getSystemEmailTemplateResponse(),emailContent.getSubject(),emailContent.getBody(),null);
} }
public EmailContentResponse prepareEmailContent( public EmailContentResponse prepareEmailContent(
@@ -131,7 +134,7 @@ public class EmailNotificationDao {
return new EmailContentResponse(subject, body, systemEmailTemplateResponse); return new EmailContentResponse(subject, body, systemEmailTemplateResponse);
} }
private void sendEmails(ApplicationEntity applicationEntity, UserEntity userEntity, List<String> additionalRecipients,Long amendmentId,SystemEmailTemplateResponse systemEmailTemplateResponse,String subject,String body) { private void sendEmails(ApplicationEntity applicationEntity, UserEntity userEntity, List<String> additionalRecipients,Long amendmentId,SystemEmailTemplateResponse systemEmailTemplateResponse,String subject,String body,Long contractId) {
Optional<ApplicationEvaluationEntity> applicationEvaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId()); Optional<ApplicationEvaluationEntity> applicationEvaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId());
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId()); CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
@@ -140,23 +143,9 @@ public class EmailNotificationDao {
applicationAmendmentRequest = applicationAmendmentRequestDao.validateApplicationAmendmentRequest(amendmentId); applicationAmendmentRequest = applicationAmendmentRequestDao.validateApplicationAmendmentRequest(amendmentId);
} }
List<AttachmentRequest> attachmentRequests =new ArrayList<>(); List<AttachmentRequest> attachmentRequests =new ArrayList<>();
S3DocxProcessor processor = new S3DocxProcessor(s3Client);
List<String> urls=new ArrayList<>(); List<String> urls=new ArrayList<>();
Map<String, String> replacements=new HashMap<>();
List<DocumentEntity> documentEntities=new ArrayList<>(); List<DocumentEntity> documentEntities=new ArrayList<>();
if(systemEmailTemplateResponse.getEmailScenario().equals(EmailScenarioTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED)) { if(systemEmailTemplateResponse.getEmailScenario().equals(EmailScenarioTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED)) {
String amount=Utils.convertToItalianFormat(String.valueOf(applicationEntity.getAmountAccepted()));
String protocolNumber=applicationEntity.getProtocol().getExternalProtocolNumber();
if(protocolNumber==null){
protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
}
replacements = Map.of(
"{call_name}", applicationEntity.getCall().getName(),
"{amount_accepted}", amount,
"{pec}", "bandi.gepafin@legalmail.it",
"{company_name}", company.getCompanyName(),
"{protocol_number}", protocolNumber
);
if(Boolean.TRUE.equals(AmendmentDocumentTypeEnum.ALTRE_GARANZIE.getValue().equals(applicationAmendmentRequest.getAmendmentDocumentType()))){ if(Boolean.TRUE.equals(AmendmentDocumentTypeEnum.ALTRE_GARANZIE.getValue().equals(applicationAmendmentRequest.getAmendmentDocumentType()))){
documentEntities=documentRepository.findBySourceInAndIsDeletedFalse(List.of(applicationAmendmentRequest.getAmendmentDocumentType(),"MODELLO_AUTOCERTIFICAZIONE","MODELLO_PRIVACY")); documentEntities=documentRepository.findBySourceInAndIsDeletedFalse(List.of(applicationAmendmentRequest.getAmendmentDocumentType(),"MODELLO_AUTOCERTIFICAZIONE","MODELLO_PRIVACY"));
}else { }else {
@@ -177,24 +166,20 @@ public class EmailNotificationDao {
: new HashSet<>(documentIds); : new HashSet<>(documentIds);
documentEntities=documentRepository.findAllByIdInAndIsDeletedFalse(setOfDocumentIds); documentEntities=documentRepository.findAllByIdInAndIsDeletedFalse(setOfDocumentIds);
} }
if(Boolean.TRUE.equals(userEntity.getHub().getUniqueUuid().equals(defaultHubUuid)) && Boolean.TRUE.equals(systemEmailTemplateResponse.getEmailScenario().equals(EmailScenarioTypeEnum.APPLICATION_CONTRACT_CREATED))) {
ApplicationContractEntity applicationContractEntity=applicationContractDao.validateApplicationContract(contractId);
List<Long> documentIds=applicationDao.validateDocumentIds(applicationContractEntity.getInstructorDocument());
Set<Long> setOfDocumentIds = (documentIds == null)
? Collections.emptySet()
: new HashSet<>(documentIds);
documentEntities=documentRepository.findAllByIdInAndIsDeletedFalse(setOfDocumentIds);
}
urls = documentEntities.stream() urls = documentEntities.stream()
.map(DocumentEntity::getFilePath) // or getUrl() .map(DocumentEntity::getFilePath) // or getUrl()
.collect(Collectors.toList()); .collect(Collectors.toList());
if(Boolean.FALSE.equals(urls.isEmpty())) {
Map<String, AttachmentRequest> processedFiles = null;
try {
processedFiles = processor.processFiles(urls, replacements);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (Map.Entry<String, AttachmentRequest> entry : processedFiles.entrySet()) {
AttachmentRequest attachmentRequest = new AttachmentRequest();
attachmentRequest.setName(entry.getKey()); // e.g. "path/file1.docx"
attachmentRequest.setFile(entry.getValue().getFile()); // updated file content
attachmentRequests.add(attachmentRequest);
}
}
UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId()); UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId());
String companyEmail = userWithCompany.getEmail(); String companyEmail = userWithCompany.getEmail();
String contactEmail = userWithCompany.getContactEmail(); String contactEmail = userWithCompany.getContactEmail();
@@ -206,26 +191,29 @@ public class EmailNotificationDao {
recipientEmails.add(userWithCompany.getPec()); recipientEmails.add(userWithCompany.getPec());
} }
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY,company.getId() , EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY,company.getId() ,
String.valueOf(recipientEmails), userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); String.valueOf(recipientEmails), userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, recipientEmails, emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, recipientEmails, emailLogEntity);
} }
else { else {
if (companyEmail != null && !companyEmail.isEmpty()) { if (companyEmail != null && !companyEmail.isEmpty()) {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY, company.getId(), EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY, company.getId(),
companyEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); companyEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, List.of(companyEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, List.of(companyEmail), emailLogEntity);
} }
if (contactEmail != null && !contactEmail.isEmpty() && !contactEmail.equals(companyEmail)) { if (contactEmail != null && !contactEmail.isEmpty() && !contactEmail.equals(companyEmail)) {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY, company.getId(), EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY, company.getId(),
contactEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); contactEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, List.of(contactEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, List.of(contactEmail), emailLogEntity);
} }
} }
if (userEntity.getBeneficiary().getEmail() != null) { if (userEntity.getBeneficiary()!= null) {
String beneficiaryEmail = null; String beneficiaryEmail = null;
RecipientTypeEnum recipientTypeEnum=RecipientTypeEnum.BENEFICIARY; RecipientTypeEnum recipientTypeEnum=RecipientTypeEnum.BENEFICIARY;
if (Boolean.TRUE.equals(userEntity.getHub().getUniqueUuid().equals(defaultHubUuid))){ if (Boolean.TRUE.equals(userEntity.getHub().getUniqueUuid().equals(defaultHubUuid))){
@@ -235,16 +223,18 @@ public class EmailNotificationDao {
beneficiaryEmail=userEntity.getBeneficiary().getEmail(); beneficiaryEmail=userEntity.getBeneficiary().getEmail();
} }
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), recipientTypeEnum,userEntity.getBeneficiary().getId() , EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), recipientTypeEnum,userEntity.getBeneficiary().getId() ,
beneficiaryEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); beneficiaryEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, List.of(beneficiaryEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, List.of(beneficiaryEmail), emailLogEntity);
} }
if (Boolean.TRUE.equals(userEntity.getHub().getUniqueUuid().equals(defaultHubUuid)) && userEntity.getBeneficiary() != null) { if (Boolean.TRUE.equals(userEntity.getHub().getUniqueUuid().equals(defaultHubUuid)) && userEntity.getBeneficiary() != null) {
String beneficiaryEmail = userEntity.getBeneficiary().getEmail(); String beneficiaryEmail = userEntity.getBeneficiary().getEmail();
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.BENEFICIARY, userEntity.getBeneficiary().getId(), EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.BENEFICIARY, userEntity.getBeneficiary().getId(),
beneficiaryEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); beneficiaryEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, List.of(beneficiaryEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, List.of(beneficiaryEmail), emailLogEntity);
} }
if(userEntity.getHub().getEmail() != null){ if(userEntity.getHub().getEmail() != null){
String hubEmails = userEntity.getHub().getEmail(); String hubEmails = userEntity.getHub().getEmail();
@@ -253,19 +243,21 @@ public class EmailNotificationDao {
hubEmail = hubEmail.trim(); hubEmail = hubEmail.trim();
if (!hubEmail.isEmpty()) { if (!hubEmail.isEmpty()) {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.PROPERTIES,null, EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.PROPERTIES,null,
hubEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); hubEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, List.of(hubEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, List.of(hubEmail), emailLogEntity);
} }
} }
} }
if (GepafinConstant.RINALDO_EMAIL.equals(rinaldoEmail)) { if (GepafinConstant.RINALDO_EMAIL.equals(rinaldoEmail)) {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.PROPERTIES,null , EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.PROPERTIES,null ,
rinaldoEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); rinaldoEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
//SMTP //SMTP
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(null, subject, body, List.of(rinaldoEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(null, subject, body, List.of(rinaldoEmail), emailLogEntity);
} }
if (applicationEvaluationEntity.isPresent()) { if (applicationEvaluationEntity.isPresent()) {
Long preInstructorId = applicationEvaluationEntity.get().getUserId(); // Assuming UserEntity has an email field Long preInstructorId = applicationEvaluationEntity.get().getUserId(); // Assuming UserEntity has an email field
@@ -273,9 +265,10 @@ public class EmailNotificationDao {
String preInstructorEmail = instructorUser.getEmail(); String preInstructorEmail = instructorUser.getEmail();
if (preInstructorEmail != null && !preInstructorEmail.isEmpty()) { if (preInstructorEmail != null && !preInstructorEmail.isEmpty()) {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.INSTRUCTOR, instructorUser.getId(), EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.INSTRUCTOR, instructorUser.getId(),
preInstructorEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId()); preInstructorEmail, userEntity.getId(), applicationEntity.getId(), amendmentId, applicationEntity.getCall().getId(),subject,body);
emailLogRequest.setAttachments(attachmentRequests); emailLogRequest.setAttachments(attachmentRequests);
sendMail(applicationEntity.getHubId(), subject, body, List.of(preInstructorEmail), emailLogRequest); EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,urls);
sendMail(applicationEntity.getHubId(), subject, body, List.of(preInstructorEmail), emailLogEntity);
} }
} }
} }
@@ -424,18 +417,31 @@ public class EmailNotificationDao {
sendEmail(applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.INADMISSIBILITY_TEMPLATE, bodyPlaceholders, null,null,emailType); sendEmail(applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.INADMISSIBILITY_TEMPLATE, bodyPlaceholders, null,null,emailType);
} }
public void sendMail(Long hubId, String subject, String body, List<String> recipientEmails, EmailLogRequest emailLogRequest) { public void sendMail(Long hubId, String subject, String body, List<String> recipientEmails, EmailLogEntity emailLogEntity) {
EmailConfig emailConfig = new EmailConfig(); EmailConfig emailConfig = new EmailConfig();
Boolean isSendEmail=Boolean.TRUE;
HubEntity hubEntity = hubRepository.findById(hubId).orElseThrow(() -> new IllegalArgumentException("Invalid Hub ID: " + hubId));
if(Boolean.TRUE.equals(hubEntity.getUniqueUuid().equals(defaultHubUuid))){
if(Boolean.TRUE.equals(emailLogEntity.getEmailType().equals(EmailScenarioTypeEnum.APPLICATION_TECHNICAL_EVALUATION_REJECTED.getValue()))
|| Boolean.TRUE.equals(emailLogEntity.getEmailType().equals(EmailScenarioTypeEnum.APPLICATION_ADMISSIBLE.getValue()))
|| Boolean.TRUE.equals(emailLogEntity.getEmailType().equals(EmailScenarioTypeEnum.APPLICATION_REJECTED.getValue()))
|| Boolean.TRUE.equals(emailLogEntity.getEmailType().equals(EmailScenarioTypeEnum.APPLICATION_AMENDMENT_REQUESTED.getValue()))) {
isSendEmail = Boolean.FALSE;
}
}
if (recipientEmails.stream().anyMatch(email -> email.equals(GepafinConstant.RINALDO_EMAIL))) { if (recipientEmails.stream().anyMatch(email -> email.equals(GepafinConstant.RINALDO_EMAIL))) {
emailConfig.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE.getValue()); emailConfig.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE.getValue());
EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType()); EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType());
emailService.sendEmail(subject, body, recipientEmails, emailConfig, emailLogRequest); emailService.sendEmail(subject, body, recipientEmails, emailConfig,emailLogEntity,isSendEmail);
} else { } else {
emailConfig = retrieveEmailConfig(hubId); emailConfig = retrieveEmailConfig(hubId);
EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType()); EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType());
emailService.sendEmail(subject, body, recipientEmails, emailConfig, emailLogRequest); emailService.sendEmail(subject, body, recipientEmails, emailConfig,emailLogEntity,isSendEmail);
} }
} }
public EmailConfig retrieveEmailConfig(Long hubId) { public EmailConfig retrieveEmailConfig(Long hubId) {
@@ -514,4 +520,48 @@ public class EmailNotificationDao {
sendEmail(applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED, bodyPlaceholders, null, sendEmail(applicationEntity, SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED, bodyPlaceholders, null,
applicationAmendmentRequestEntity.getId(),null); applicationAmendmentRequestEntity.getId(),null);
} }
public void sendEmailForApplicationContracted(ApplicationEntity applicationEntity,ApplicationContractEntity applicationContractEntity,UserEntity user) {
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{call_name}}", applicationEntity.getCall().getName());
String protocolNumber=applicationEntity.getProtocol().getExternalProtocolNumber();
if(protocolNumber==null){
protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
}
bodyPlaceholders.put("{{protocol_number}}", protocolNumber);
String protocolDate= DateTimeUtil.formatLocalDateTime(applicationEntity.getProtocol().getCreatedDate(), GepafinConstant.DD_MM_YYYY);
if(applicationEntity.getProtocol().getExternalProtocolDate()!=null){
protocolDate= DateTimeUtil.formatLocalDateTime(applicationEntity.getProtocol().getExternalProtocolDate(), GepafinConstant.DD_MM_YYYY);
}
bodyPlaceholders.put("{{protocol_date}}", protocolDate);
bodyPlaceholders.put("{{protocol_time}}", DateTimeUtil.parseLocalTimeToString(applicationEntity.getProtocol().getTime(), GepafinConstant.HH_MM_SS));
HubEntity hubEntity = hubService.valdateHub(applicationEntity.getHubId());
Map<String, String> subjectPlaceholders = new HashMap<>();
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
subjectPlaceholders.put("{{call_name}}", applicationEntity.getCall().getName());
subjectPlaceholders.put("{{company_name}}", company.getCompanyName());
// bodyPlaceholders.put("{{legal_mail}}", legalMail);
String subject = Utils.replacePlaceholders(applicationContractEntity.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(applicationContractEntity.getText(), bodyPlaceholders);
SystemEmailTemplateResponse systemEmailTemplateResponse=new SystemEmailTemplateResponse();
systemEmailTemplateResponse.setSubject(subject);
systemEmailTemplateResponse.setHtmlContent(body);
systemEmailTemplateResponse.setEmailScenario(EmailScenarioTypeEnum.APPLICATION_CONTRACT_CREATED);
EmailContentResponse emailContentResponse= new EmailContentResponse(subject, body, systemEmailTemplateResponse);
sendEmails(applicationEntity, user, null,null,emailContentResponse.getSystemEmailTemplateResponse(),emailContentResponse.getSubject(),emailContentResponse.getBody(),applicationContractEntity.getId());
}
public void sendPendingMail(Long hubId, String subject, String body, List<String> recipientEmails, EmailLogEntity emailLogEntity) {
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,emailLogEntity,true);
} else {
emailConfig = retrieveEmailConfig(hubId);
EmailService emailService = emailServiceFactory.getEmailService(emailConfig.getEmailServiceType());
emailService.sendEmail(subject, body, recipientEmails, emailConfig,emailLogEntity,true);
}
}
} }

View File

@@ -29,6 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -105,7 +106,11 @@ public class NotificationDao {
String userChannel = GepafinConstant.COMMON_SINGLE_CHANNEL_PREFIX + userId; String userChannel = GepafinConstant.COMMON_SINGLE_CHANNEL_PREFIX + userId;
log.info("Channel for User {}", userChannel); log.info("Channel for User {}", userChannel);
NotificationResponse notificationResponse = convertNotificationEntityToNotificationResponse(notificationEntity); NotificationResponse notificationResponse = convertNotificationEntityToNotificationResponse(notificationEntity);
try {
messagingTemplate.convertAndSend(userChannel, notificationResponse); messagingTemplate.convertAndSend(userChannel, notificationResponse);
} catch (Exception e) {
log.error("Error while sending the notification {0}", e);
}
} }
private void sendToCompanies(Long userId, List<Long> companyIds, NotificationEntity notificationEntity) { private void sendToCompanies(Long userId, List<Long> companyIds, NotificationEntity notificationEntity) {
@@ -120,7 +125,11 @@ public class NotificationDao {
notificationEntity.setUserWithCompany(userWithCompany); notificationEntity.setUserWithCompany(userWithCompany);
notificationRepository.save(notificationEntity); notificationRepository.save(notificationEntity);
NotificationResponse notificationResponse = convertNotificationEntityToNotificationResponse(notificationEntity); NotificationResponse notificationResponse = convertNotificationEntityToNotificationResponse(notificationEntity);
try {
messagingTemplate.convertAndSend(companyChannel, notificationResponse); messagingTemplate.convertAndSend(companyChannel, notificationResponse);
} catch (Exception e) {
log.error("Error while sending the notification {0}", e);
}
}); });
} }

View File

@@ -0,0 +1,146 @@
package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest;
import liquibase.util.Validate;
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.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.response.EmailLogResponse;
import net.gepafin.tendermanagement.model.response.PecEmailLogResponse;
import net.gepafin.tendermanagement.model.response.PecMailResponse;
import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.repositories.UserActionsRepository;
import net.gepafin.tendermanagement.service.ApplicationService;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@Log4j2
public class PecMailDao {
@Autowired
private Validator validator;
@Autowired
private UserActionsRepository userActionsRepository;
@Autowired
private EmailLogRepository emailLogRepository;
@Autowired
private CallService callService;
@Autowired
private EmailNotificationDao emailNotificationDao;
@Autowired
private ApplicationService applicationService;
public List<PecMailResponse> sendPecMail(HttpServletRequest request, List<Long> userActionIds) {
List<PecMailResponse> pecMailResponses=new ArrayList<>();
for (Long userActionId: userActionIds) {
List<EmailLogEntity> emailLogs = getEmailLogEntities(request, userActionId);
for (EmailLogEntity log : emailLogs) {
List<String> recipients = Utils.commaSeparatedStringToList(log.getRecipientEmails());
CallEntity call = callService.validateCall(log.getCallId());
emailNotificationDao.sendPendingMail(
call.getHub().getId(),
log.getEmailSubject(),
log.getEmailBody(),
recipients,
log
);
ApplicationEntity applicationEntity=applicationService.validateApplication(log.getApplicationId());
String callName=applicationEntity.getCall().getName();
PecMailResponse pecMailResponse=createPecMailResponse(log.getUserAction().getId(),log,callName);
pecMailResponses.add(pecMailResponse);
}
}
return pecMailResponses;
}
private List<EmailLogEntity> getEmailLogEntities(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));
}
validator.validateHubId(request, userActionEntity.getHubId());
List<EmailLogEntity> emailLogs = emailLogRepository.findByUserActionIdAndSendStatusAndIsDeletedFalse(userActionId,StatusTypeEnum.PENDING.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));
}
return emailLogs;
}
public List<PecEmailLogResponse> getEmailLogByUserActionId(HttpServletRequest request,Long userActionId){
List<EmailLogEntity> emailLogs = getEmailLogEntities(request, userActionId);
ApplicationEntity applicationEntity=applicationService.validateApplication(emailLogs.get(0).getApplicationId());
String callName=applicationEntity.getCall().getName();
List<PecEmailLogResponse> pecEmailLogResponses=new ArrayList<>();
for(EmailLogEntity emailLogEntity:emailLogs) {
PecEmailLogResponse pecEmailLogResponse = createPecEmailLogResponse(userActionId, emailLogEntity, callName);
pecEmailLogResponses.add(pecEmailLogResponse);
}
return pecEmailLogResponses;
}
private PecEmailLogResponse createPecEmailLogResponse(Long userActionId, EmailLogEntity emailLogEntity, String callName) {
PecEmailLogResponse pecEmailLogResponse = new PecEmailLogResponse();
pecEmailLogResponse.setId(emailLogEntity.getId());
pecEmailLogResponse.setUserActionId(userActionId);
pecEmailLogResponse.setUserId(emailLogEntity.getUserId());
pecEmailLogResponse.setApplicationId(emailLogEntity.getApplicationId());
pecEmailLogResponse.setCallName(callName);
EmailLogResponse emailLogResponse=new EmailLogResponse();
emailLogResponse.setRecipientId(emailLogEntity.getRecipientId());
emailLogResponse.setRecipientType(emailLogEntity.getRecipientType());
pecEmailLogResponse.setEmailLogs(emailLogResponse);
pecEmailLogResponse.setType(emailLogEntity.getEmailType());
pecEmailLogResponse.setSubject(emailLogEntity.getEmailSubject());
pecEmailLogResponse.setHtmlContent(emailLogEntity.getEmailBody());
pecEmailLogResponse.setCallId(emailLogEntity.getCallId());
return pecEmailLogResponse;
}
private PecMailResponse createPecMailResponse(Long userActionId, EmailLogEntity emailLogEntity, String callName) {
PecMailResponse pecMailResponse = new PecMailResponse();
pecMailResponse.setId(emailLogEntity.getId());
pecMailResponse.setUserActionId(userActionId);
pecMailResponse.setUserId(emailLogEntity.getUserId());
pecMailResponse.setApplicationId(emailLogEntity.getApplicationId());
pecMailResponse.setCallName(callName);
pecMailResponse.setType(emailLogEntity.getEmailType());
pecMailResponse.setSubject(emailLogEntity.getEmailSubject());
pecMailResponse.setHtmlContent(emailLogEntity.getEmailBody());
pecMailResponse.setCallId(emailLogEntity.getCallId());
return pecMailResponse;
}
public List<PecMailResponse> getAllEmailLogs(HttpServletRequest request) {
List<EmailLogEntity> emailLogs=emailLogRepository.findPendingPECEmailLogs();
List<PecMailResponse> pecMailResponses=new ArrayList<>();
for (EmailLogEntity emailLogEntity: emailLogs){
ApplicationEntity applicationEntity=applicationService.validateApplication(emailLogEntity.getApplicationId());
String callName=applicationEntity.getCall().getName();
PecMailResponse pecMailResponse=createPecMailResponse(emailLogEntity.getUserAction().getId(),emailLogEntity,callName);
pecMailResponses.add(pecMailResponse);
}
return pecMailResponses;
}
}

View File

@@ -15,27 +15,28 @@ public class S3PathConfig {
@Autowired @Autowired
S3ConfigRepository s3ConfigRepository; S3ConfigRepository s3ConfigRepository;
public String generateDocumentPath(DocumentSourceTypeEnum type, Long callId, Long applicationId,Long amendmentId,Long communicationId) { public String generateDocumentPath(DocumentSourceTypeEnum type, Long callId, Long applicationId,Long amendmentId,Long communicationId,Long contractId) {
S3ConfigEntity config = getDocumentPath(type); S3ConfigEntity config = getDocumentPath(type);
return config.getParentFolder() + "/" + buildS3Path(config.getPath(), callId, applicationId,amendmentId,communicationId); return config.getParentFolder() + "/" + buildS3Path(config.getPath(), callId, applicationId,amendmentId,communicationId,contractId);
} }
public String generateDocumentPathForOther(DocOtherSourceTypeEnum type, Long callId, Long applicationId,Long amendmentId,Long communicationId) { public String generateDocumentPathForOther(DocOtherSourceTypeEnum type, Long callId, Long applicationId,Long amendmentId,Long communicationId,Long contractId) {
S3ConfigEntity config = getDocumentPathForOther(type); S3ConfigEntity config = getDocumentPathForOther(type);
return config.getParentFolder() + "/" + buildS3Path(config.getPath(), callId, applicationId,amendmentId,communicationId); return config.getParentFolder() + "/" + buildS3Path(config.getPath(), callId, applicationId,amendmentId,communicationId,contractId);
} }
public String generateDocumentPathForDelegationAndSignedDocument(DocOtherSourceTypeEnum type) { public String generateDocumentPathForDelegationAndSignedDocument(DocOtherSourceTypeEnum type) {
S3ConfigEntity config = getDocumentPathForOther(type); S3ConfigEntity config = getDocumentPathForOther(type);
return config.getParentFolder() + "/" + config.getPath(); return config.getParentFolder() + "/" + config.getPath();
} }
private String buildS3Path(String pathTemplate, Long callId, Long applicationId, Long amendmentId,Long communicationId) { private String buildS3Path(String pathTemplate, Long callId, Long applicationId, Long amendmentId,Long communicationId,Long contractId) {
return pathTemplate return pathTemplate
.replace("{call_id}", callId != null && callId != 0L ? "call_" + callId : "") .replace("{call_id}", callId != null && callId != 0L ? "call_" + callId : "")
.replace("{application_id}", applicationId != null && applicationId != 0L ? "application_" + applicationId : "") .replace("{application_id}", applicationId != null && applicationId != 0L ? "application_" + applicationId : "")
.replace("{amendment_id}", amendmentId != null && amendmentId != 0L ? "amendment_" + amendmentId : "") .replace("{amendment_id}", amendmentId != null && amendmentId != 0L ? "amendment_" + amendmentId : "")
.replace("{communication_id}", communicationId != null && communicationId != 0L ? "communication_" + communicationId : ""); .replace("{communication_id}", communicationId != null && communicationId != 0L ? "communication_" + communicationId : "")
.replace("{contract_id}", contractId != null && contractId != 0L ? "contract_" + contractId : "");
} }
private S3ConfigEntity getDocumentPath(DocumentSourceTypeEnum type) { private S3ConfigEntity getDocumentPath(DocumentSourceTypeEnum type) {

View File

@@ -192,19 +192,19 @@ public class UserDao {
: SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.USER_ONBOARDING_BANDI; : SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.USER_ONBOARDING_BANDI;
emailTemplate = systemEmailTemplatesService.retrieveTemplateByTypeAndCall(templateType, userEntity.getHub(), null); emailTemplate = systemEmailTemplatesService.retrieveTemplateByTypeAndCall(templateType, userEntity.getHub(), null);
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, userEntity.getId(), userEntity.getEmail(),
userEntity.getId(), null, null, null);
Map<String, String> placeholders = replacePlaceholders(userEntity, userReq); Map<String, String> placeholders = replacePlaceholders(userEntity, userReq);
String body = Utils.replacePlaceholders(emailTemplate.getHtmlContent(), placeholders); String body = Utils.replacePlaceholders(emailTemplate.getHtmlContent(), placeholders);
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, userEntity.getId(), userEntity.getEmail(),
userEntity.getId(), null, null, null,emailTemplate.getSubject(),body);
EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail( emailNotificationDao.sendMail(
userEntity.getHub().getId(), userEntity.getHub().getId(),
emailTemplate.getSubject(), emailTemplate.getSubject(),
body, body,
List.of(userEntity.getEmail()), List.of(userEntity.getEmail()),
emailLogRequest emailLogEntity
); );
} }
@@ -545,15 +545,7 @@ public class UserDao {
redirectUrl = user.getHub().getDomainName(); redirectUrl = user.getHub().getDomainName();
} }
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(
emailTemplate.getEmailScenario(),
RecipientTypeEnum.USER,
user.getId(),
user.getEmail(),
user.getId(),
null,
null,
null);
redirectUrl = String.format( redirectUrl = String.format(
user.getHub().getDomainName() + GepafinConstant.RESET_PASSWORD_URL_FORMAT, user.getHub().getDomainName() + GepafinConstant.RESET_PASSWORD_URL_FORMAT,
token, token,
@@ -569,12 +561,22 @@ public class UserDao {
"{{user_name}}", userName, "{{user_name}}", userName,
"{{reset_password_link}}", redirectUrl "{{reset_password_link}}", redirectUrl
)); ));
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(
emailTemplate.getEmailScenario(),
RecipientTypeEnum.USER,
user.getId(),
user.getEmail(),
user.getId(),
null,
null,
null,subject,body);
EmailLogEntity emailLogEntity=emailLogDao.createEmailLog(emailLogRequest,null);
emailNotificationDao.sendMail( emailNotificationDao.sendMail(
user.getHub().getId(), user.getHub().getId(),
subject, subject,
body, body,
List.of(user.getEmail()), List.of(user.getEmail()),
emailLogRequest emailLogEntity
); );
log.info("Password reset token email sent to: {}", user.getEmail()); log.info("Password reset token email sent to: {}", user.getEmail());

View File

@@ -0,0 +1,46 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.Data;
import org.hibernate.annotations.Where;
import java.time.LocalDateTime;
@Entity
@Table(name = "APPLICATION_CONTRACT")
@Data
@Where(clause = "is_deleted = false")
public class ApplicationContractEntity extends BaseEntity{
@Column(name = "SUBJECT")
private String subject;
@Column(name = "TEXT")
private String text;
@Column(name = "INSTRUCTOR_DOCUMENT")
private String instructorDocument;
@Column(name = "STATUS")
private String status;
@Column(name = "BENEFICIARY_DOCUMENT")
private String beneficiaryDocument;
@Column(name = "BENEFICIARY_USER_ID")
private Long beneficiaryUserId;
@Column(name = "INSTRUCTOR_ID")
private Long instructorId;
@Column(name = "IS_DELETED")
private Boolean isDeleted;
@Column(name = "COMPLETION_DATE")
private LocalDateTime completionDate;
@Column(name = "APPLICATION_ID")
private Long applicationId;
}

View File

@@ -59,5 +59,8 @@ public class EmailLogEntity extends BaseEntity{
@ManyToOne @ManyToOne
@JoinColumn(name = "user_action_id") @JoinColumn(name = "user_action_id")
private UserActionEntity userAction; private UserActionEntity userAction;
@Column(name = "ATTACHMENTS")
private String attachments;
} }

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum ApplicationContractStatusEnum {
DRAFT("DRAFT"),
SIGNED("SIGNED");
private final String value;
ApplicationContractStatusEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}

View File

@@ -18,7 +18,9 @@ public enum ApplicationStatusTypeEnum {
ADMISSIBLE("ADMISSIBLE"), ADMISSIBLE("ADMISSIBLE"),
TECHNICAL_EVALUATION("TECHNICAL_EVALUATION"), TECHNICAL_EVALUATION("TECHNICAL_EVALUATION"),
TECHNICAL_EVALUATION_REJECTED("TECHNICAL_EVALUATION_REJECTED"), TECHNICAL_EVALUATION_REJECTED("TECHNICAL_EVALUATION_REJECTED"),
AWAITING_TECHNICAL_EVALUATION("AWAITING_TECHNICAL_EVALUATION") ; AWAITING_TECHNICAL_EVALUATION("AWAITING_TECHNICAL_EVALUATION"),
AWAITING_CONTRACT("AWAITING_CONTRACT"),
CONTRACT_SIGNED("CONTRACT_SIGNED");
private String value; private String value;

View File

@@ -8,7 +8,11 @@ public enum AssignedApplicationEnum {
AWAITING("AWAITING"), AWAITING("AWAITING"),
CLOSE("CLOSE"); CLOSE("CLOSE"),
AWAITING_CONTRACT("AWAITING_CONTRACT"),
CONTRACT_SIGNED("CONTRACT_SIGNED");
private final String value; private final String value;

View File

@@ -6,7 +6,8 @@ public enum DocumentSourceTypeEnum {
APPLICATION("APPLICATION"), APPLICATION("APPLICATION"),
EVALUATION("EVALUATION"), EVALUATION("EVALUATION"),
AMENDMENT("AMENDMENT"), AMENDMENT("AMENDMENT"),
COMMUNICATION("COMMUNICATION"); COMMUNICATION("COMMUNICATION"),
CONTRACT("CONTRACT");
private String value; private String value;

View File

@@ -14,7 +14,8 @@ public enum EmailScenarioTypeEnum {
APPLICATION_REJECTED("APPLICATION_REJECTED"), APPLICATION_REJECTED("APPLICATION_REJECTED"),
APPLICATION_SUBMISSION_FAILURE("APPLICATION_SUBMISSION_FAILURE"), APPLICATION_SUBMISSION_FAILURE("APPLICATION_SUBMISSION_FAILURE"),
APPLICATION_TECHNICAL_EVALUATION_REJECTED("APPLICATION_TECHNICAL_EVALUATION_REJECTED"), APPLICATION_TECHNICAL_EVALUATION_REJECTED("APPLICATION_TECHNICAL_EVALUATION_REJECTED"),
SPECIAL_APPLICATION_AMENDMENT_REQUESTED("SPECIAL_APPLICATION_AMENDMENT_REQUESTED"); SPECIAL_APPLICATION_AMENDMENT_REQUESTED("SPECIAL_APPLICATION_AMENDMENT_REQUESTED"),
APPLICATION_CONTRACT_CREATED("APPLICATION_CONTRACT_CREATED");
private final String value; private final String value;

View File

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

View File

@@ -3,7 +3,7 @@ package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonValue;
public enum StatusTypeEnum { public enum StatusTypeEnum {
PENDING ("PENDING"),
SUCCESS ("SUCCESS"), SUCCESS ("SUCCESS"),
FAILED("FAILED"); FAILED("FAILED");

View File

@@ -224,7 +224,16 @@ public enum UserActionContextEnum {
RESEND_EMAIL("RESEND_EMAIL"), RESEND_EMAIL("RESEND_EMAIL"),
SEND_REMINDER_EMAIL("SEND_REMINDER_EMAIL"), SEND_REMINDER_EMAIL("SEND_REMINDER_EMAIL"),
CREATE_SPECIAL_AMENDMENT("CREATE_SPECIAL_AMENDMENT"), CREATE_SPECIAL_AMENDMENT("CREATE_SPECIAL_AMENDMENT"),
UPDATE_APPLICATION_TO_TECHNICAL_EVALUATION_REJECTED("UPDATE_APPLICATION_TO_TECHNICAL_EVALUATION_REJECTED"); UPDATE_APPLICATION_TO_TECHNICAL_EVALUATION_REJECTED("UPDATE_APPLICATION_TO_TECHNICAL_EVALUATION_REJECTED"),
CREATE_CONTRACT_FOR_APPLICATION("CREATE_CONTRACT_FOR_APPLICATION"),
UPDATE_APPLICATION_CONTRACT("UPDATE_APPLICATION_CONTRACT"),
FETCH_APPLICATION_CONTRACT("FETCH_APPLICATION_CONTRACT"),
FETCH_APPLICATION_CONTRACT_BY_APPLICATION_ID("FETCH_APPLICATION_CONTRACT_BY_APPLICATION_ID"),
FETCH_APPLICATION_CONTRACT_BY_BENEFICIARY_USER_ID("FETCH_APPLICATION_CONTRACT_BY_BENEFICIARY_USER_ID"),
SEND_PEC_MAIL("SEND_PEC_MAIL"),
FETCH_EMAIL_LOG("FETCH_EMAIL_LOG"),
FETCH_ALL_EMAIL_LOG("FETCH_ALL_EMAIL_LOG");
private final String value; private final String value;

View File

@@ -0,0 +1,10 @@
package net.gepafin.tendermanagement.model.request;
import lombok.Data;
@Data
public class ApplicationContractRequest {
private String subject;
private String text;
}

View File

@@ -0,0 +1,28 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.enums.ApplicationContractStatusEnum;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class ApplicationContractResponse {
private Long id;
private ApplicationContractStatusEnum status;
private Long instructorId;
private List<DocumentResponseBean> beneficiaryDocuments;
private Long beneficiaryUserId;
private LocalDateTime completionDate;
private Long applicationId;
private String callName;
}

View File

@@ -50,5 +50,7 @@ public class ApplicationEvaluationFormResponse {
private String companyCodiceAteco; private String companyCodiceAteco;
private List<EmailSendResponse> emailSendResponse; private List<EmailSendResponse> emailSendResponse;
private ApplicationSignedDocumentResponse signedDocument; private ApplicationSignedDocumentResponse signedDocument;
private ApplicationContractResponse contract;
} }

View File

@@ -52,5 +52,6 @@ public class ApplicationEvaluationResponse {
private List<EmailSendResponse> emailSendResponse; private List<EmailSendResponse> emailSendResponse;
private List<DocumentResponseBean> rejectedDocument; private List<DocumentResponseBean> rejectedDocument;
private ApplicationSignedDocumentResponse signedDocument; private ApplicationSignedDocumentResponse signedDocument;
private ApplicationContractResponse contract;
} }

View File

@@ -23,6 +23,7 @@ public class AssignedApplicationViewResponse extends BaseBean {
private String companyName; private String companyName;
private String assignedUserName; private String assignedUserName;
private List<EmailSendResponse> emailSendResponse; private List<EmailSendResponse> emailSendResponse;
private ApplicationContractResponse contract;
} }

View File

@@ -0,0 +1,12 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
@Data
public class EmailLogResponse {
private String recipientType;
private Long recipientId;
}

View File

@@ -0,0 +1,30 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import java.util.List;
@Data
public class PecEmailLogResponse {
private Long id;
private Long userActionId;
private Long userId;
private Long applicationId;
private String callName;
private EmailLogResponse emailLogs;
private String type;
private String subject;
private String htmlContent;
private Long callId;
}

View File

@@ -0,0 +1,28 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import java.util.List;
@Data
public class PecMailResponse {
private Long id;
private Long userActionId;
private Long userId;
private Long applicationId;
private String callName;
private String type;
private String subject;
private String htmlContent;
private Long callId;
}

View File

@@ -59,7 +59,7 @@ public interface ApplicationAmendmentRequestRepository extends JpaRepository<App
@Query("SELECT a FROM ApplicationAmendmentRequestEntity a " + @Query("SELECT a FROM ApplicationAmendmentRequestEntity a " +
"WHERE a.isDeleted = false " + "WHERE a.isDeleted = false " +
"AND a.status NOT IN('CLOSE','EXPIRED') " + "AND a.status NOT IN('CLOSE','EXPIRED','RESPONSE_RECEIVED') " +
"AND a.endDate < :currentTime") "AND a.endDate < :currentTime")
List<ApplicationAmendmentRequestEntity> findAmendmentsDueForExpiration(LocalDateTime currentTime); List<ApplicationAmendmentRequestEntity> findAmendmentsDueForExpiration(LocalDateTime currentTime);

View File

@@ -0,0 +1,18 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.ApplicationContractEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ApplicationContractRepository extends JpaRepository<ApplicationContractEntity,Long> {
ApplicationContractEntity findByIdAndIsDeletedFalse(Long id);
ApplicationContractEntity findByApplicationIdAndIsDeletedFalse(Long applicationId);
List<ApplicationContractEntity> findByBeneficiaryUserIdAndStatusAndIsDeletedFalse(Long applicationId,String status);
}

View File

@@ -3,6 +3,7 @@ package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.EmailLogEntity; import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.entities.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@@ -23,6 +24,13 @@ public interface EmailLogRepository extends JpaRepository<EmailLogEntity,Long> {
String sendStatus String sendStatus
); );
List<EmailLogEntity> findByUserActionIdAndSendStatusAndIsDeletedFalse(Long userActionId,String status);
@Query(value = """
SELECT DISTINCT ON (user_action_id) * FROM gepafin_schema.email_log WHERE send_status = 'PENDING' AND is_deleted = false""", nativeQuery = true)
List<EmailLogEntity> findPendingPECEmailLogs();
} }

View File

@@ -0,0 +1,21 @@
package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.ApplicationContractRequest;
import net.gepafin.tendermanagement.model.response.ApplicationContractResponse;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface ApplicationContractService {
public ApplicationContractResponse createApplicationContract(HttpServletRequest httpServletRequest, Long applicationId, List<MultipartFile> beneficiaryContractDocuments);
// public ApplicationContractResponse updateApplicationContract(HttpServletRequest httpServletRequest, Long applicationContractId,List<MultipartFile> beneficiaryContractDocuments);
public ApplicationContractResponse getContractById(Long contractId);
public ApplicationContractResponse getContractByApplicationId(Long applicationContractId);
List<ApplicationContractResponse> getContractByBeneficiaryUserId(Long beneficiaryUserId);
}

View File

@@ -0,0 +1,16 @@
package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.response.PecEmailLogResponse;
import net.gepafin.tendermanagement.model.response.PecMailResponse;
import java.util.List;
public interface PecMailService {
public List<PecMailResponse> sendPecMail(HttpServletRequest request, List<Long> userActionIds);
public List<PecEmailLogResponse> getEmailLogByUserActionId(HttpServletRequest request, Long userActionId);
public List<PecMailResponse> getAllEmailLogs(HttpServletRequest request);
}

View File

@@ -0,0 +1,68 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.ApplicationContractDao;
import net.gepafin.tendermanagement.dao.UserDao;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.ApplicationContractRequest;
import net.gepafin.tendermanagement.model.response.ApplicationContractResponse;
import net.gepafin.tendermanagement.service.ApplicationContractService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
@Service
public class ApplicationContractServiceImpl implements ApplicationContractService {
@Autowired
private ApplicationContractDao applicationContractDao;
@Autowired
private Validator validator;
@Autowired
private UserDao userDao;
@Override
public ApplicationContractResponse createApplicationContract(HttpServletRequest httpServletRequest, Long applicationId, List<MultipartFile> beneficiaryContractDocuments) {
UserEntity user= validator.validateUser(httpServletRequest);
if(beneficiaryContractDocuments==null) {
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.FILES_REQUIRED_FOR_CONTRACT));
}
beneficiaryContractDocuments.forEach(Utils::validateFileType);
return applicationContractDao.createApplicationContract(applicationId,beneficiaryContractDocuments,user);
}
//
// @Override
// public ApplicationContractResponse updateApplicationContract(HttpServletRequest httpServletRequest, Long applicationContractId, List<MultipartFile> beneficiaryContractDocuments) {
// UserEntity user= validator.validateUser(httpServletRequest);
// if(beneficiaryContractDocuments==null) {
// throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.FILES_REQUIRED_FOR_CONTRACT));
// }
// return applicationContractDao.updateApplicationContract(applicationContractId,beneficiaryContractDocuments,user);
// }
@Override
public ApplicationContractResponse getContractById(Long contractId) {
return applicationContractDao.getContractById(contractId);
}
@Override
public ApplicationContractResponse getContractByApplicationId(Long applicationId) {
return applicationContractDao.getContractByApplicationId(applicationId);
}
@Override
public List<ApplicationContractResponse> getContractByBeneficiaryUserId(Long beneficiaryUserId) {
UserEntity user=userDao.validateUser(beneficiaryUserId);
return applicationContractDao.getContractByBeneficiaryUserId(user);
}
}

View File

@@ -1,12 +1,13 @@
package net.gepafin.tendermanagement.service.impl; package net.gepafin.tendermanagement.service.impl;
import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.model.request.EmailConfig; import net.gepafin.tendermanagement.model.request.EmailConfig;
import net.gepafin.tendermanagement.model.request.EmailLogRequest; import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import java.util.List; import java.util.List;
public interface EmailService { public interface EmailService {
void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogRequest emailLogRequest); void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogEntity emailLogEntity,Boolean isSendEmail);
} }

View File

@@ -8,6 +8,8 @@ import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum; import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailConfig; import net.gepafin.tendermanagement.model.request.EmailConfig;
import net.gepafin.tendermanagement.model.request.EmailLogRequest; import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Utils; import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator; import net.gepafin.tendermanagement.util.Validator;
@@ -15,6 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
@@ -30,8 +33,11 @@ public class MailgunEmailService implements EmailService {
@Autowired @Autowired
private EmailLogDao emailLogDao; private EmailLogDao emailLogDao;
@Autowired
private EmailLogRepository emailLogRepository;
@Override @Override
public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogRequest emailLogRequest) { public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogEntity emailLogEntity,Boolean isSendEmail) {
if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) { if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) {
return; return;
@@ -45,10 +51,9 @@ public class MailgunEmailService implements EmailService {
// Send email via Mailgun API // Send email via Mailgun API
HttpResponse<String> response2=null; HttpResponse<String> response2=null;
if (Boolean.FALSE.equals(validator.isTestProfileActivated())) { if (Boolean.FALSE.equals(validator.isTestProfileActivated())) {
emailLogRequest.setEmailSubject(subject); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailBody(body); emailLogEntity.setSendStatus(StatusTypeEnum.SUCCESS.getValue());
emailLogRequest.setSendStatus(StatusTypeEnum.SUCCESS.getValue()); emailLogEntity.setRecipientEmails(Utils.listToCommaSeparatedString(recipientEmails));
emailLogRequest.setRecipientEmails(Utils.listToCommaSeparatedString(recipientEmails));
try { try {
Unirest.setTimeouts(0, 0); Unirest.setTimeouts(0, 0);
response2 = Unirest.post(url) response2 = Unirest.post(url)
@@ -60,16 +65,17 @@ public class MailgunEmailService implements EmailService {
.field("html", body) .field("html", body)
.asString(); .asString();
}catch(Exception e) { }catch(Exception e) {
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue()); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.MAILGUN_SERVICE); emailLogEntity.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setErrorMessage(e.getMessage()); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.MAILGUN_SERVICE.getValue());
EmailLogEntity emailLogEntity= emailLogDao.createEmailLog(emailLogRequest); emailLogEntity.setErrorMessage(e.getMessage());
emailLogRepository.save(emailLogEntity);
throw new RuntimeException("Failed to send email via Mailgun: " + response2.getStatus()); throw new RuntimeException("Failed to send email via Mailgun: " + response2.getStatus());
} }
emailLogRequest.setEmailServiceResponse(response2.getBody()); emailLogEntity.setEmailServiceResponse(response2.getBody());
} }
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.MAILGUN_SERVICE); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.MAILGUN_SERVICE.getValue());
EmailLogEntity emailLogEntity= emailLogDao.createEmailLog(emailLogRequest); emailLogRepository.save(emailLogEntity);
} }
} }

View File

@@ -1,5 +1,6 @@
package net.gepafin.tendermanagement.service.impl; package net.gepafin.tendermanagement.service.impl;
import com.amazonaws.services.s3.AmazonS3Client;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.HttpResponse;
@@ -9,14 +10,18 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.ApplicationDao; import net.gepafin.tendermanagement.dao.ApplicationDao;
import net.gepafin.tendermanagement.dao.EmailLogDao; import net.gepafin.tendermanagement.dao.EmailLogDao;
import net.gepafin.tendermanagement.dao.NotificationDao; import net.gepafin.tendermanagement.dao.NotificationDao;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.EmailLogEntity;
import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum; import net.gepafin.tendermanagement.enums.EmailScenarioTypeEnum;
import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum; import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.NotificationTypeEnum; import net.gepafin.tendermanagement.enums.NotificationTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum; import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailConfig; import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.request.EmailLogRequest; import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.model.request.NotificationReq; import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.model.request.PecEmailRequest; import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.S3DocxProcessor;
import net.gepafin.tendermanagement.util.Utils; import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator; import net.gepafin.tendermanagement.util.Validator;
@@ -25,6 +30,9 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -51,29 +59,72 @@ public class PecEmailService implements EmailService {
@Autowired @Autowired
private ApplicationDao applicationDao; private ApplicationDao applicationDao;
@Autowired
private CompanyService companyService;
@Autowired
private AmazonS3Client s3Client;
@Autowired
private EmailLogRepository emailLogRepository;
@Override @Override
public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogRequest emailLogRequest) { public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogEntity emailLogEntity, Boolean isSendEmail) {
if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) { if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) {
return; return;
} }
if(Boolean.TRUE.equals(isSendEmail)) {
Map<String, String> replacements=new HashMap<>();
List<AttachmentRequest> attachmentRequests =new ArrayList<>();
S3DocxProcessor processor = new S3DocxProcessor(s3Client);
List<String> urls = Utils.convertJsonStringToList(emailLogEntity.getAttachments(), String.class);
if(emailLogEntity.getEmailType().equals(EmailScenarioTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED.getValue())) {
ApplicationEntity applicationEntity = applicationDao.validateApplication(emailLogEntity.getApplicationId());
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
String amount = Utils.convertToItalianFormat(String.valueOf(applicationEntity.getAmountAccepted()));
String protocolNumber = applicationEntity.getProtocol().getExternalProtocolNumber();
if (protocolNumber == null) {
protocolNumber = String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
}
replacements = Map.of(
"{call_name}", applicationEntity.getCall().getName(),
"{amount_accepted}", amount,
"{pec}", "bandi.gepafin@legalmail.it",
"{company_name}", company.getCompanyName(),
"{protocol_number}", protocolNumber
);
}
if (urls!=null && Boolean.FALSE.equals(urls.isEmpty())) {
Map<String, AttachmentRequest> processedFiles = null;
try {
processedFiles = processor.processFiles(urls, replacements);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (Map.Entry<String, AttachmentRequest> entry : processedFiles.entrySet()) {
AttachmentRequest attachmentRequest = new AttachmentRequest();
attachmentRequest.setName(entry.getKey()); // e.g. "path/file1.docx"
attachmentRequest.setFile(entry.getValue().getFile()); // updated file content
attachmentRequests.add(attachmentRequest);
}
}
PecEmailRequest emailRequest = new PecEmailRequest(); PecEmailRequest emailRequest = new PecEmailRequest();
emailRequest.setSender(emailConfig.getSender()); emailRequest.setSender(emailConfig.getSender());
emailRequest.setSubject(subject); emailRequest.setSubject(subject);
emailRequest.setBody(body); emailRequest.setBody(body);
emailRequest.setUsername(emailConfig.getUsername()); emailRequest.setUsername(emailConfig.getUsername());
emailRequest.setPassword(emailConfig.getPassword()); emailRequest.setPassword(emailConfig.getPassword());
emailRequest.setAttachments(emailLogRequest.getAttachments()); emailRequest.setAttachments(attachmentRequests);
emailRequest.setRecipient(recipientEmails); emailRequest.setRecipient(recipientEmails);
String url = emailConfig.getUrl() + GepafinConstant.PEC_SERVICE_SEND_MAIL; String url = emailConfig.getUrl() + GepafinConstant.PEC_SERVICE_SEND_MAIL;
String authToken = emailConfig.getAuthToken(); String authToken = emailConfig.getAuthToken();
HttpResponse<String> response2 = null; HttpResponse<String> response2 = null;
if (Boolean.FALSE.equals(validator.isTestProfileActivated())) { if (Boolean.FALSE.equals(validator.isTestProfileActivated())) {
emailLogRequest.setEmailSubject(emailRequest.getSubject()); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailBody(emailRequest.getBody()); emailLogEntity.setSendStatus(StatusTypeEnum.SUCCESS.getValue());
emailLogRequest.setSendStatus(StatusTypeEnum.SUCCESS.getValue()); emailLogEntity.setRecipientEmails(Utils.listToCommaSeparatedString(emailRequest.getRecipient()));
emailLogRequest.setRecipientEmails(Utils.listToCommaSeparatedString(emailRequest.getRecipient()));
try { try {
if (Boolean.TRUE.equals(Boolean.parseBoolean(isPecServiceEnabled))) { if (Boolean.TRUE.equals(Boolean.parseBoolean(isPecServiceEnabled))) {
Unirest.setTimeouts(0, 0); Unirest.setTimeouts(0, 0);
@@ -85,31 +136,34 @@ public class PecEmailService implements EmailService {
if (!isSuccessfulPecResponse(response2.getBody())) { if (!isSuccessfulPecResponse(response2.getBody())) {
String errorMsg = "PEC sending failed: " + response2.getBody(); String errorMsg = "PEC sending failed: " + response2.getBody();
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue()); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE); emailLogEntity.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setErrorMessage(errorMsg); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE.getValue());
sendNotificationOnFailure(emailLogRequest.getUserId(),emailLogRequest.getEmailType()); emailLogEntity.setErrorMessage(errorMsg);
sendNotificationOnFailure(emailLogEntity.getUserId(), EmailScenarioTypeEnum.valueOf(emailLogEntity.getEmailType()));
if (EmailScenarioTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED.equals(emailLogRequest.getEmailType())) { if (EmailScenarioTypeEnum.APPLICATION_SUBMITTED.getValue().equals(emailLogEntity.getEmailType())) {
applicationDao.sendApplicationSubmissionFailureEmail(emailLogRequest); applicationDao.sendApplicationSubmissionFailureEmail(emailLogEntity);
} }
} }
} }
} catch (Exception e) { } catch (Exception e) {
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue()); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE); emailLogEntity.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setErrorMessage(e.getMessage()); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE.getValue());
sendNotificationOnFailure(emailLogRequest.getUserId(),emailLogRequest.getEmailType()); emailLogEntity.setErrorMessage(e.getMessage());
if (EmailScenarioTypeEnum.SPECIAL_APPLICATION_AMENDMENT_REQUESTED.equals(emailLogRequest.getEmailType())) { sendNotificationOnFailure(emailLogEntity.getUserId(), EmailScenarioTypeEnum.valueOf(emailLogEntity.getEmailType()));
applicationDao.sendApplicationSubmissionFailureEmail(emailLogRequest); if (EmailScenarioTypeEnum.APPLICATION_SUBMITTED.getValue().equals(emailLogEntity.getEmailType())) {
applicationDao.sendApplicationSubmissionFailureEmail(emailLogEntity);
} }
} }
if (response2 != null) { if (response2 != null) {
emailLogRequest.setEmailServiceResponse(response2.getBody()); emailLogEntity.setEmailServiceResponse(response2.getBody());
} }
} }
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE); }
emailLogDao.createEmailLog(emailLogRequest); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.PEC_SERVICE.getValue());
emailLogRepository.save(emailLogEntity);
} }
private void sendNotificationOnFailure(Long userId, EmailScenarioTypeEnum emailScenarioTypeEnum) { private void sendNotificationOnFailure(Long userId, EmailScenarioTypeEnum emailScenarioTypeEnum) {

View File

@@ -0,0 +1,33 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.PecMailDao;
import net.gepafin.tendermanagement.model.response.PecEmailLogResponse;
import net.gepafin.tendermanagement.model.response.PecMailResponse;
import net.gepafin.tendermanagement.service.PecMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PecMailSerivceImpl implements PecMailService {
@Autowired
private PecMailDao pecMailDao;
@Override
public List<PecMailResponse> sendPecMail(HttpServletRequest request, List<Long> userActionIds) {
return pecMailDao.sendPecMail(request,userActionIds);
}
@Override
public List<PecEmailLogResponse> getEmailLogByUserActionId(HttpServletRequest request, Long userActionId) {
return pecMailDao.getEmailLogByUserActionId(request,userActionId);
}
@Override
public List<PecMailResponse> getAllEmailLogs(HttpServletRequest request) {
return pecMailDao.getAllEmailLogs(request);
}
}

View File

@@ -9,6 +9,7 @@ import com.amazonaws.services.s3.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.gepafin.tendermanagement.dao.DocumentDao; import net.gepafin.tendermanagement.dao.DocumentDao;
import net.gepafin.tendermanagement.dao.S3PathConfig; import net.gepafin.tendermanagement.dao.S3PathConfig;
import net.gepafin.tendermanagement.entities.ApplicationContractEntity;
import net.gepafin.tendermanagement.entities.ApplicationEntity; import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.CommunicationEntity; import net.gepafin.tendermanagement.entities.CommunicationEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity; import net.gepafin.tendermanagement.entities.DocumentEntity;
@@ -81,6 +82,9 @@ public class S3ReUploadMigrationService {
@Autowired @Autowired
private DocumentDao documentDao; private DocumentDao documentDao;
@Autowired
private ApplicationContractRepository applicationContractRepository;
private boolean migrationCompleted = false; private boolean migrationCompleted = false;
@@ -114,6 +118,7 @@ public class S3ReUploadMigrationService {
Long amendmentId = null; Long amendmentId = null;
Long evaluationId = null; Long evaluationId = null;
Long communicationId=null; Long communicationId=null;
Long contractId=null;
if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(document.getSource())) { if (DocumentSourceTypeEnum.CALL.getValue().equalsIgnoreCase(document.getSource())) {
callId = document.getSourceId(); callId = document.getSourceId();
} else if (DocumentSourceTypeEnum.APPLICATION.getValue().equalsIgnoreCase(document.getSource())) { } else if (DocumentSourceTypeEnum.APPLICATION.getValue().equalsIgnoreCase(document.getSource())) {
@@ -138,9 +143,15 @@ public class S3ReUploadMigrationService {
applicationId = applicationEntity.getId(); applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId(); callId = applicationEntity.getCall().getId();
} }
else if(DocumentSourceTypeEnum.CONTRACT.getValue().equalsIgnoreCase(document.getSource())){
contractId = document.getSourceId();
ApplicationContractEntity applicationContractEntity=applicationContractRepository.findByIdAndIsDeletedFalse(contractId);
ApplicationEntity applicationEntity=applicationService.validateApplication(applicationContractEntity.getApplicationId());
applicationId = applicationEntity.getId();
callId = applicationEntity.getCall().getId();
}
documentDao.deleteFileFromS3(document,callId,applicationId,amendmentId,communicationId,contractId);
documentDao.deleteFileFromS3(document,callId,applicationId,amendmentId,communicationId);
processDocuments++; processDocuments++;
} catch (Exception e) { } catch (Exception e) {
@@ -231,10 +242,10 @@ public class S3ReUploadMigrationService {
Long callId; Long callId;
if (sourceType.equals(DocumentSourceTypeEnum.CALL)) { if (sourceType.equals(DocumentSourceTypeEnum.CALL)) {
return s3ConfigBean.generateDocumentPath(sourceType, document.getSourceId(), 0L,0L,0L); return s3ConfigBean.generateDocumentPath(sourceType, document.getSourceId(), 0L,0L,0L,0L);
} else { } else {
callId = applicationRepository.findCallIdById(document.getSourceId()); callId = applicationRepository.findCallIdById(document.getSourceId());
return s3ConfigBean.generateDocumentPath(sourceType, callId, document.getSourceId(),0L,0L); return s3ConfigBean.generateDocumentPath(sourceType, callId, document.getSourceId(),0L,0L,0L);
} }
} }

View File

@@ -9,6 +9,8 @@ import net.gepafin.tendermanagement.enums.EmailServiceTypeEnum;
import net.gepafin.tendermanagement.enums.StatusTypeEnum; import net.gepafin.tendermanagement.enums.StatusTypeEnum;
import net.gepafin.tendermanagement.model.request.EmailConfig; import net.gepafin.tendermanagement.model.request.EmailConfig;
import net.gepafin.tendermanagement.model.request.EmailLogRequest; import net.gepafin.tendermanagement.model.request.EmailLogRequest;
import net.gepafin.tendermanagement.repositories.EmailLogRepository;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Utils; import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator; import net.gepafin.tendermanagement.util.Validator;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -17,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@Component @Component
@@ -43,19 +46,21 @@ public class SystemEmailService implements EmailService {
@Autowired @Autowired
private EmailLogDao emailLogDao; private EmailLogDao emailLogDao;
@Autowired
private EmailLogRepository emailLogRepository;
public final Logger log = LoggerFactory.getLogger(SystemEmailService.class); public final Logger log = LoggerFactory.getLogger(SystemEmailService.class);
public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogRequest emailLogRequest) { public void sendEmail(String subject, String body, List<String> recipientEmails, EmailConfig emailConfig, EmailLogEntity emailLogEntity,Boolean isSendEmail) {
if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) { if (Boolean.FALSE.equals(Boolean.parseBoolean(isEmailSendingEnabled))) {
return; return;
} }
if (Boolean.TRUE.equals(isSendEmail)) {
emailLogRequest.setEmailSubject(subject); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailBody(body); emailLogEntity.setSendStatus(StatusTypeEnum.SUCCESS.getValue());
emailLogRequest.setSendStatus(StatusTypeEnum.SUCCESS.getValue()); emailLogEntity.setRecipientEmails(Utils.listToCommaSeparatedString(recipientEmails));
emailLogRequest.setRecipientEmails(Utils.listToCommaSeparatedString(recipientEmails)); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE.getValue());
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE);
if (Boolean.FALSE.equals(validator.isTestProfileActivated())) { if (Boolean.FALSE.equals(validator.isTestProfileActivated())) {
MessageResponse response = null; MessageResponse response = null;
try { try {
@@ -66,20 +71,23 @@ public class SystemEmailService implements EmailService {
response = mailgunMessagesApi.sendMessage(mailGunDomainName, message); response = mailgunMessagesApi.sendMessage(mailGunDomainName, message);
} catch (Exception e) { } catch (Exception e) {
emailLogRequest.setSendStatus(StatusTypeEnum.FAILED.getValue()); emailLogEntity.setSendDateTime(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
emailLogRequest.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE); emailLogEntity.setSendStatus(StatusTypeEnum.FAILED.getValue());
emailLogRequest.setErrorMessage(e.getMessage()); emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE.getValue());
emailLogDao.createEmailLog(emailLogRequest); emailLogEntity.setErrorMessage(e.getMessage());
emailLogRepository.save(emailLogEntity);
throw new RuntimeException("Failed to send email via Mailgun: " + (response != null ? response.getMessage() : "No response from Mailgun"), e); throw new RuntimeException("Failed to send email via Mailgun: " + (response != null ? response.getMessage() : "No response from Mailgun"), e);
} }
if (response != null) { if (response != null) {
emailLogRequest.setEmailServiceResponse(response.toString()); emailLogEntity.setEmailServiceResponse(response.toString());
} }
emailLogDao.createEmailLog(emailLogRequest);
} }
} }
emailLogEntity.setEmailServiceType(EmailServiceTypeEnum.SYSTEM_EMAIL_SERVICE.getValue());
emailLogRepository.save(emailLogEntity);
}
} }

View File

@@ -139,7 +139,7 @@ public class UserSignedAndDelegationServiceImpl {
private String generateNewS3PathForDelegationDoc() { private String generateNewS3PathForDelegationDoc() {
return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_DELEGATION, 0L, 0L,0L,0L); return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_DELEGATION, 0L, 0L,0L,0L,0L);
} }
private String generateNewS3PathForUserSignedDoc(ApplicationSignedDocumentEntity document) { private String generateNewS3PathForUserSignedDoc(ApplicationSignedDocumentEntity document) {

View File

@@ -0,0 +1,95 @@
package net.gepafin.tendermanagement.web.rest.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import net.gepafin.tendermanagement.model.request.ApplicationAmendmentSpecialRequest;
import net.gepafin.tendermanagement.model.request.ApplicationContractRequest;
import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
import net.gepafin.tendermanagement.model.response.ApplicationAmendmentRequestResponse;
import net.gepafin.tendermanagement.model.response.ApplicationContractResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Validated
public interface ApplicationContractApi {
@Operation(summary = "Api to create application contract",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@PostMapping(value = "/application/{applicationId}", produces = "application/json", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@PreAuthorize( "hasRole('ROLE_SUPER_ADMIN') || hasRole('ROLE_BENEFICIARY') || hasRole('ROLE_CONFIDI')")
ResponseEntity<Response<ApplicationContractResponse>> createApplicationContract(HttpServletRequest request,
@Parameter(description = "Application ID", required = true) @PathVariable("applicationId") Long applicationId, @Parameter(description = "List of files to upload", required = true)
@RequestPart(required = true) List<MultipartFile> beneficiaryContractDocuments);
// @Operation(summary = "Api to update application contract from beneficiary side",
// responses = {
// @ApiResponse(responseCode = "200", description = "OK"),
// @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
// @ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
// @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
// @ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
// @ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
// @ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
// @PutMapping(value = "{applicationContractId}", produces = "application/json", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
// @PreAuthorize( "hasRole('ROLE_SUPER_ADMIN') || hasRole('ROLE_BENEFICIARY') || hasRole('ROLE_CONFIDI')")
// ResponseEntity<Response<ApplicationContractResponse>> updateApplicationContract(HttpServletRequest request,
// @Parameter(description = "Application Contract ID", required = true) @PathVariable("applicationContractId") Long applicationContractId, @Parameter(description = "List of files to upload", required = true)
// @RequestPart(required = true) List<MultipartFile> beneficiaryContractDocuments);
@Operation(summary = "Api to get an application contract by id",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "{id}", produces = "application/json")
ResponseEntity<Response<ApplicationContractResponse>> getApplicationContractById(HttpServletRequest request,@Parameter(description = "The application contract id", required = true) @PathVariable(value = "id", required = true) Long id);
@Operation(summary = "Api to get an application contract by application id",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/application", produces = "application/json")
ResponseEntity<Response<ApplicationContractResponse>> getApplicationContractByApplicationId(HttpServletRequest request,@Parameter(description = "The application id", required = true) @RequestParam(value = "applicationId", required = true) Long applicationId);
@Operation(summary = "Api to get an application contract by beneficiary user id",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/user", produces = "application/json")
ResponseEntity<Response< List<ApplicationContractResponse>>> getApplicationContractByBeneficiaryUserId(HttpServletRequest request,@Parameter(description = "The user id", required = true) @RequestParam(value = "userId", required = true) Long userId);
}

View File

@@ -35,7 +35,7 @@ public interface DashboardApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) }) @ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "", @GetMapping(value = "",
produces = { "application/json" }) produces = { "application/json" })
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN') || hasRole('ROLE_INSTRUCTOR_MANAGER')") @PreAuthorize("hasRole('ROLE_SUPER_ADMIN') || hasRole('ROLE_INSTRUCTOR_MANAGER') || hasRole('ROLE_DIRECTOR')")
ResponseEntity<Response<SuperAdminWidgetResponseBean>> getDashboardWidgetForSuperAdmin(HttpServletRequest request); ResponseEntity<Response<SuperAdminWidgetResponseBean>> getDashboardWidgetForSuperAdmin(HttpServletRequest request);
@Operation(summary = "Api to get dashboard widget for beneficiary", @Operation(summary = "Api to get dashboard widget for beneficiary",

View File

@@ -0,0 +1,56 @@
package net.gepafin.tendermanagement.web.rest.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.NotificationReq;
import net.gepafin.tendermanagement.model.response.NotificationResponse;
import net.gepafin.tendermanagement.model.response.PecEmailLogResponse;
import net.gepafin.tendermanagement.model.response.PecMailResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
public interface PecMailApi {
@Operation(summary = "Api to send mail from pec.", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.NOTFOUND_ERROR_EXAMPLE))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.BADREQUEST_ERROR_EXAMPLE))) })
@PostMapping(value = "/userAction", produces = "application/json")
ResponseEntity<Response< List<PecMailResponse>>> sendPecMail(HttpServletRequest request,
@Parameter(description = "The user action id", required = true) @RequestParam("userActionIds") List<Long> userActionIds);
@Operation(summary = "Api to get email log by user action id", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.NOTFOUND_ERROR_EXAMPLE))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.BADREQUEST_ERROR_EXAMPLE))) })
@GetMapping(value = "/userAction/{userActionId}", produces = "application/json")
ResponseEntity<Response<List<PecEmailLogResponse>>> getEmailLogByUserActionId(HttpServletRequest request,
@Parameter(description = "The user action id", required = true) @PathVariable("userActionId") Long userActionId);
@Operation(summary = "Api to get all email logs", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.NOTFOUND_ERROR_EXAMPLE))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(value =
ErrorConstants.BADREQUEST_ERROR_EXAMPLE))) })
@GetMapping(value = "",produces = "application/json")
ResponseEntity<Response<List<PecMailResponse>>> getAllEmailLogs(HttpServletRequest request);
}

View File

@@ -0,0 +1,86 @@
package net.gepafin.tendermanagement.web.rest.api.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.enums.UserActionContextEnum;
import net.gepafin.tendermanagement.enums.UserActionLogsEnum;
import net.gepafin.tendermanagement.model.request.ApplicationContractRequest;
import net.gepafin.tendermanagement.model.request.UserActionRequest;
import net.gepafin.tendermanagement.model.response.ApplicationContractResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.service.ApplicationContractService;
import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.web.rest.api.ApplicationContractApi;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("${openapi.gepafin.base-path:/v1/applicationContract}")
public class ApplicationContractApiController implements ApplicationContractApi {
@Autowired
private LoggingUtil loggingUtil;
@Autowired
private ApplicationContractService applicationContractService;
@Override
public ResponseEntity<Response<ApplicationContractResponse>> createApplicationContract(HttpServletRequest request, Long applicationId, List<MultipartFile> beneficiaryContractDocuments) {
loggingUtil.logUserAction(
UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.INSERT).actionContext(UserActionContextEnum.CREATE_CONTRACT_FOR_APPLICATION).build());
ApplicationContractResponse applicationContractResponse=applicationContractService.createApplicationContract(request,applicationId,beneficiaryContractDocuments);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(applicationContractResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.CREATE_APPLICATION_CONTRACT)));
}
// @Override
// public ResponseEntity<Response<ApplicationContractResponse>> updateApplicationContract(HttpServletRequest request, Long applicationId, List<MultipartFile> beneficiaryContractDocuments) {
// loggingUtil.logUserAction(
// UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.UPDATE).actionContext(UserActionContextEnum.UPDATE_APPLICATION_CONTRACT).build());
// ApplicationContractResponse applicationContractResponse=applicationContractService.updateApplicationContract(request,applicationId,beneficiaryContractDocuments);
//
// return ResponseEntity.status(HttpStatus.OK)
// .body(new Response<>(applicationContractResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.APPLICATION_CONTRACT_UPDATED)));
// }
@Override
public ResponseEntity<Response<ApplicationContractResponse>> getApplicationContractById(HttpServletRequest request, Long id) {
loggingUtil.logUserAction(
UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.VIEW).actionContext(UserActionContextEnum.FETCH_APPLICATION_CONTRACT).build());
ApplicationContractResponse applicationContractResponse=applicationContractService.getContractById(id);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(applicationContractResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.APPLICATION_CONTRACT_FETCHED)));
}
@Override
public ResponseEntity<Response<ApplicationContractResponse>> getApplicationContractByApplicationId(HttpServletRequest request, Long applicationId) {
loggingUtil.logUserAction(
UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.VIEW).actionContext(UserActionContextEnum.FETCH_APPLICATION_CONTRACT_BY_APPLICATION_ID).build());
ApplicationContractResponse applicationContractResponse=applicationContractService.getContractByApplicationId(applicationId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(applicationContractResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.APPLICATION_CONTRACT_FETCHED)));
}
@Override
public ResponseEntity<Response<List<ApplicationContractResponse>>> getApplicationContractByBeneficiaryUserId(HttpServletRequest request, Long beneficiaryUserId) {
loggingUtil.logUserAction(
UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.VIEW).actionContext(UserActionContextEnum.FETCH_APPLICATION_CONTRACT_BY_BENEFICIARY_USER_ID).build());
List<ApplicationContractResponse> applicationContractResponse=applicationContractService.getContractByBeneficiaryUserId(beneficiaryUserId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(applicationContractResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.APPLICATION_CONTRACT_FETCHED)));
}
}

View File

@@ -0,0 +1,69 @@
package net.gepafin.tendermanagement.web.rest.api.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.enums.UserActionContextEnum;
import net.gepafin.tendermanagement.enums.UserActionLogsEnum;
import net.gepafin.tendermanagement.model.request.UserActionRequest;
import net.gepafin.tendermanagement.model.response.ApplicationAmendmentRequestResponse;
import net.gepafin.tendermanagement.model.response.PecEmailLogResponse;
import net.gepafin.tendermanagement.model.response.PecMailResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.service.PecMailService;
import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.web.rest.api.PecMailApi;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("${openapi.gepafin.base-path:/v1/pecMail}")
public class PecMailController implements PecMailApi {
@Autowired
private LoggingUtil loggingUtil;
@Autowired
private PecMailService pecMailService;
@Override
public ResponseEntity<Response< List<PecMailResponse>>> sendPecMail(HttpServletRequest request,List<Long> userActionIds) {
loggingUtil.logUserAction(UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.EMAIL)
.actionContext(UserActionContextEnum.SEND_PEC_MAIL).build());
List<PecMailResponse> pecMailResponse=pecMailService.sendPecMail(request,userActionIds);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(pecMailResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.MAIL_SENT_SUCCESSFULLY)));
}
@Override
public ResponseEntity<Response<List<PecEmailLogResponse>>> getEmailLogByUserActionId(HttpServletRequest request, Long userActionId) {
loggingUtil.logUserAction(UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.EMAIL)
.actionContext(UserActionContextEnum.FETCH_EMAIL_LOG).build());
List<PecEmailLogResponse> pecEmailLogResponse=pecMailService.getEmailLogByUserActionId(request,userActionId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(pecEmailLogResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.EMAIL_LOG_FETCHED)));
}
@Override
public ResponseEntity<Response<List<PecMailResponse>>> getAllEmailLogs(HttpServletRequest request) {
loggingUtil.logUserAction(UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.EMAIL)
.actionContext(UserActionContextEnum.FETCH_ALL_EMAIL_LOG).build());
List<PecMailResponse> pecMailResponses=pecMailService.getAllEmailLogs(request);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(pecMailResponses, Status.SUCCESS, Translator.toLocale(GepafinConstant.EMAIL_LOG_FETCHED)));
}
}

View File

@@ -19,7 +19,7 @@ default.hub.uuid=p4lk3bcx1RStqTaIVVbXs
#Login to Odessa, Appointment Creation, Upload document Configuration #Login to Odessa, Appointment Creation, Upload document Configuration
appointment.base.url=https://demo.galileonetwork.it/gateway/rest appointment.base.url=https://demo.galileonetwork.it/gateway/rest
appointment.portal.user=UtenzaAPIPortal@621 appointment.portal.user=UtenzaAPIPortal@621
appointment.portal.password=u13nzaAP1P0rtal! appointment.portal.password=Sardegna2025!
appointment.portal.source=GEPAFINPORTAL appointment.portal.source=GEPAFINPORTAL
appointment.portal.context=GEPAFINPORTAL appointment.portal.context=GEPAFINPORTAL

View File

@@ -2955,6 +2955,13 @@
</addColumn> </addColumn>
</changeSet> </changeSet>
<changeSet id="03-06-2025_RK_182045" author="Rajesh Khore">
<addColumn tableName="application_amendment_request">
<column name="extended_days" type="INTEGER"></column>
<column name="extension_date" type="TIMESTAMP WITHOUT TIME ZONE"></column>
</addColumn>
</changeSet>
<changeSet id="05-06-2025_RK_191738" author="Rajesh Khore"> <changeSet id="05-06-2025_RK_191738" author="Rajesh Khore">
<sqlFile dbms="postgresql" <sqlFile dbms="postgresql"
path="db/dump/updated_form_field_05_06_2025.sql"/> path="db/dump/updated_form_field_05_06_2025.sql"/>
@@ -2980,6 +2987,13 @@
</addColumn> </addColumn>
</changeSet> </changeSet>
<changeSet id="26-06-2025_RK_110723" author="Rajesh Khore">
<sql dbms="postgresql">select
setval('gepafin_schema.ndganag_id_seq', (select
max(id)+1
from gepafin_schema.ndganag), false)
</sql>
</changeSet>
<changeSet id="27-06-2025_RK_155914" author="Rajesh Khore"> <changeSet id="27-06-2025_RK_155914" author="Rajesh Khore">
<sqlFile dbms="postgresql" <sqlFile dbms="postgresql"
path="db/dump/insert_system_email_template_technical_evaluation_rejected.sql"/> path="db/dump/insert_system_email_template_technical_evaluation_rejected.sql"/>
@@ -3008,12 +3022,6 @@
<changeSet id="23-07-2025_RK_121816" author="Rajesh Khore"> <changeSet id="23-07-2025_RK_121816" author="Rajesh Khore">
<sqlFile dbms="postgresql" path="db/dump/update_application_form_view_23_07_2025.sql"/> <sqlFile dbms="postgresql" path="db/dump/update_application_form_view_23_07_2025.sql"/>
</changeSet> </changeSet>
<changeSet id="03-06-2025_RK_182045" author="Rajesh Khore">
<addColumn tableName="application_amendment_request">
<column name="extended_days" type="INTEGER"></column>
<column name="extension_date" type="TIMESTAMP WITHOUT TIME ZONE"></column>
</addColumn>
</changeSet>
<changeSet id="29-09-2025_RK_155236" author="Rajesh Khore"> <changeSet id="29-09-2025_RK_155236" author="Rajesh Khore">
<addColumn tableName="application_amendment_request"> <addColumn tableName="application_amendment_request">
@@ -3085,7 +3093,78 @@
<sqlFile dbms="postgresql" path="db/dump/update_system_email_template_of_application_rejected_17_10_2025.sql"/> <sqlFile dbms="postgresql" path="db/dump/update_system_email_template_of_application_rejected_17_10_2025.sql"/>
</changeSet> </changeSet>
<changeSet id="23-10-2025_RK_151527" author="Rajesh Khore"> <changeSet id="23-10-2025_RK_151527" author="Rajesh Khore">
<sqlFile dbms="postgresql" path="db/dump/update_document_for_special_amendment_23-10-2025.sql"/> <sqlFile dbms="postgresql" path="db/dump/update_document_for_special_amendment_23-10-2025.sql"/>
</changeSet> </changeSet>
<changeSet id="29-10-2025_RK_164154" author="Rajesh Khore">
<createTable tableName="application_contract">
<column name="id" type="INTEGER" autoIncrement="true">
<constraints primaryKey="true" primaryKeyName="application_contract_pkey" nullable="false"/>
</column>
<column name="subject" type="VARCHAR(255)"/>
<column name="text" type="VARCHAR(255)"/>
<column name="instructor_document" type="VARCHAR(255)"/>
<column name="status" type="VARCHAR(255)"/>
<column name="beneficiary_document" type="VARCHAR(255)"/>
<column name="beneficiary_user_id" type="INTEGER"/>
<column name="instructor_id" type="INTEGER"/>
<column name="application_id" type="INTEGER"/>
<column name="is_deleted" type="BOOLEAN"/>
<column name="completion_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
<column name="created_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
</createTable>
</changeSet>
<changeSet id="02-11-2025_RK_204924" author="Rajesh Khore">
<insert tableName="s3_path_configuration">
<column name="type" value="CONTRACT"/>
<column name="path" value="call/{call_id}/application/{application_id}/contract/{contract_id}/"/>
<column name="bucket_name" value="mementoresources"/>
<column name="created_date" value="2025-11-03 00:00:00"/>
<column name="updated_date" value="2025-11-03 00:00:00"/>
<column name="parent_folder" value="gepafin/staging"/>
</insert>
</changeSet>
<changeSet id="04-11-2025_RK_151527" author="Rajesh Khore">
<sqlFile dbms="postgresql" path="db/dump/insert_notification_template_for_contract_upload.sql"/>
</changeSet>
<changeSet id="07-11-2025_RK_143942" author="Rajesh Khore">
<insert tableName="role">
<column name="role_name" value="director"/>
<column name="role_type" value="ROLE_DIRECTOR"/>
<column name="description"
value="They can evaluate email and send emails."/>
<column name="created_date" value="2025-11-07 00:00:00"/>
<column name="updated_date" value="2025-11-07 00:00:00"/>
<column name="permissions" value=""/>
<column name="region_id" valueComputed="1"/>
</insert>
<insert tableName="GEPAFIN_USER">
<column name="email" value="director@test.test"/>
<column name="password" value="$2a$10$doUyOcEm8WPuFfpFT5y18.1DvZzF7exbqgy9X0P27cUBK7YWbfzzS"/>
<column name="first_name" value="Test"/>
<column name="last_name" value="Director"/>
<column name="last_login" value="2025-11-07 00:00:00"/>
<column name="organization" value="DirectorOrg"/>
<column name="role_id" valueComputed="(SELECT id FROM role WHERE role_type = 'ROLE_DIRECTOR')"/>
<column name="status" value="ACTIVE"/>
<column name="last_login" value="2025-11-07 00:00:00"/>
<column name="address" value="789 Victory Road"/>
<column name="city" value="Naples"/>
<column name="country" value="Italy"/>
<column name="hub_id" value="1"/>
</insert>
</changeSet>
<changeSet id="10-11-2025_RK_091725" author="Rajesh Khore">
<addColumn tableName="email_log">
<column name="attachments" type="TEXT"></column>
</addColumn>
</changeSet>
</databaseChangeLog> </databaseChangeLog>

View File

@@ -0,0 +1,2 @@
INSERT INTO notification_type (notification_name,title, json_template,created_date,updated_date,is_deleted) VALUES
('CONTRACT_UPLOAD', 'Documento caricato per contratto','La richiesta in {{call_name}} con protocollo n. {{protocol_number}} ha caricato un documento per il contratto.','2025-11-04T15:16:26.472Z','2025-11-04T15:16:26.472Z','false');

View File

@@ -416,5 +416,16 @@ pec.email.required=PEC email is required.
application.technical.evaluation.rejected.success=Application changes to status application technical evaluation rejected successfully. application.technical.evaluation.rejected.success=Application changes to status application technical evaluation rejected successfully.
invalid.email.json=Invalid email json. invalid.email.json=Invalid email json.
more.fields.required=Subject, reason, and motivation are required when rejecting the application. more.fields.required=Subject, reason, and motivation are required when rejecting the application.
create.application.contract=Application contract created successfully.
application.contract.not.found=Application contract not found.
application.contract.fetched=Application contract fetched successfully.
application.contract.updated=Application contract updated successfully.
files.required.for.contract=Files are required for contract.
application.contract.already.exist=Application contract already exist for this application.
application.not.approved=Application is not approved.
subject.body.required=Subject and body is required to create contract.
mail.send.successfully=Mail sent succesfully.
email.log.fetched=Email log fetched successfully.
amendment.appropiate.status=Application amendment is not in appropiate status for this operation.

View File

@@ -400,10 +400,21 @@ application.readmit.success=L'applicazione è stata riammessa con successo.
no.email.log.msg = Nessuna email trovata per userActionId specificato. no.email.log.msg = Nessuna email trovata per userActionId specificato.
user.action.id.not.found = ID azione utente non trovato. user.action.id.not.found = ID azione utente non trovato.
ndg.not.found=NDG non trovato. ndg.not.found=NDG non trovato.
email.pec.cannot.null=L'indirizzo email pec è obbligatorio. email.pec.cannot.null=L'indirizzo email pec <EFBFBD> obbligatorio.
user.request.completed=Richiesta utente completata con successo. user.request.completed=Richiesta utente completata con successo.
end.date.greater.than.now=La data di fine deve essere successiva alla data e all'ora correnti. end.date.greater.than.now=La data di fine deve essere successiva alla data e all'ora correnti.
pec.email.required=Obbligatorio l'indirizzo e-mail PEC. pec.email.required=Obbligatorio l'indirizzo e-mail PEC.
application.technical.evaluation.rejected.success=Lo stato dell'applicazione cambia: valutazione tecnica dell'applicazione rifiutata con successo. application.technical.evaluation.rejected.success=Lo stato dell'applicazione cambia: valutazione tecnica dell'applicazione rifiutata con successo.
invalid.email.json=Codice email json non valido. invalid.email.json=Codice email json non valido.
more.fields.required=Per rifiutare la domanda sono richiesti oggetto, motivo e motivazione. more.fields.required=Per rifiutare la domanda sono richiesti oggetto, motivo e motivazione.
create.application.contract=Contratto di candidatura creato con successo.
application.contract.not.found=Contratto di candidatura non trovato.
application.contract.fetched=Contratto di candidatura recuperato con successo.
application.contract.updated=Contratto di candidatura aggiornato con successo.
files.required.for.contract=I file sono necessari per il contratto.
application.contract.already.exist=Il contratto di applicazione esiste gi<67> per questa applicazione.
application.not.approved=La domanda non <20> stata approvata.
subject.body.required=Per creare un contratto sono necessari oggetto e corpo.
mail.send.successfully=Email inviata con successo.
email.log.fetched=Registro email recuperato correttamente.
amendment.appropiate.status=L'emendamento dell'applicazione non <20> in stato appropriato per questa operazione.