diff --git a/pom.xml b/pom.xml
index a42534bf..daa067ba 100644
--- a/pom.xml
+++ b/pom.xml
@@ -251,6 +251,24 @@
0.4.8
+
+ org.apache.commons
+ commons-csv
+ 1.10.0
+
+
+
+
+
+
+
+
+ com.sun.mail
+ jakarta.mail
+ 2.0.1
+
+
+
@@ -271,8 +289,8 @@
liquibase-maven-plugin
src/main/resources/application.properties
-
-
-
+
+
+
diff --git a/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java b/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java
index a3269c36..1fe74e81 100644
--- a/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java
+++ b/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java
@@ -510,10 +510,67 @@ public class GepafinConstant {
public static final String APPLICATION_USER_ID="applicationUserId";
public static final String INVALID_USER_ID="invalid.user";
public static final String COMPANY_NAME="companyName";
+ public static final String TABLE_COLUMNS="table_columns";
+ public static final String PREDEFINED="predefined";
+ public static final String EBABLE_CSV="enableCsv";
+ public static final String LABEL_CSV="labelCsv";
+ public static final String GET="get";
+ public static final String REPORT_COLUMNS="reportColumns";
+ public static final String FIELD_TYPE="fieldtype";
+ public static final String ENABLE_FORMULA="enableFormula";
+ public static final String STATE_FIELD_DATA="stateFieldData";
+ public static final String REPORT_ENABLE="reportEnable";
+ public static final String TABLE="table";
+ public static final String GET_FIELD_TYPE="getFieldType";
+ public static final String GET_APPLICATION_FORM_ID="getApplicationFormId";
+ public static final String GET_APPLICATION_ID="getApplicationId";
+ public static final String GET_ID="getId";
+ public static final String GET_CLASS="getClass";
+ public static final String GET_FORM_ID="getFormId";
+ public static final String GET_FIELD_ID="getFieldId";
+ public static final String GET_FIELD_LABEL="getFieldLabel";
+ public static final String GET_FIELD_VALUE="getFieldValue";
+ public static final String GET_REPORT_ENABLE="getReportEnable";
+ public static final String GET_REPORT_HEADER="getReportHeader";
public static final String APPOINTMENT_ID="appointmentId";
public static final String APPLICATION_STATUS="applicationStatus";
+ public static final String RINALDO_EMAIL = "rinaldo.bonazzo@bflows.net";
+ public static final String RESEND_EMAIL_SENT_SUCCESS_MSG = "resend.email.sent.success.msg";
+ public static final String RESEND_EMAIL_SENT_FAILED_MSG = "resend.email.sent.failed.msg";
+ public static final String REMINDER_EMAIL_FAILED_MSG = "reminder.email.sent.failed.msg";
+
+ public static final String READMIT_APPLICATION_SUCCESS = "application.readmit.success";
+
+ public static final String NO_EMAIL_LOG_FOUND = "no.email.log.msg";
+ public static final String USER_ACTION_ID_NOT_FOUND = "user.action.id.not.found";
+
+ public static final String CAUSE_STRING = "cause" ;
+ public static final String ERROR_DESCRIPTION_STRING = "errorDescription" ;
+ public static final String ERROR_STRING = "errors";
+ public static final String PROTOCOL_SERVICE_URL="http://65.108.55.96:8080";
+ public static final String PROTOCOL_SERVICE_BEARER_TOKEN="/auth/login";
+ public static final String PROTOCOL_SERVICE_CREATE_PROTOCOL="/documenti/protocollaUD";
+ public static final String PROTOCOL_CALL_NAME="BANDO";
+ public static final String PROTOCOL_DOC_URL="DOC_URL";
+ public static final String PROTOCOL_COMPANY_NAME_VAT_NUMBER="OGGETTO_PG";
+ public static final String PROTOCOL_DOC_HASH="URL_CONTENT_HASH";
+ public static final String PROTOCOL_TIPO_PROTOCOLLAZIONE="TIPO_PROTOCOLLAZIONE";
+ public static final String PROTOCOL_TIPO_CORRISPONDENTE_COMPANY="tipoCorrispondente";
+ public static final String PROTOCOL_COMPANY_NAME="denominazione";
+ public static final String PROTOCOL_MEZZO="mezzo";
+ public static final String PROTOCOL_INDIRIZZO_PEC="indirizzoPec";
+ public static final String PROTOCOL_COMPANY_VAT_NUMBER="identificativo";
+ public static final String PROTOCOL_CODICE_UO="codiceUo";
+ public static final String PROTOCOL_COMPETENTE="competente";
+ public static final String PROTOCOL_TIPO_CORRISPONDENTE="tipoCorrispondente";
+ public static final String PROTOCOL_MITTENTE="mittente";
+ public static final String PROTOCOL_DESTINATARI="destinatari";
+ public static final String PROTOCOL_EXTERNAL_YEAR="ANNO_PG";
+ public static final String PROTOCOL_EXTERNAL_NUMBER="";
+ public static final String PROTOCOL_EXTERNAL_DATE="";
+
}
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java
index 2748f9bf..0cded205 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationAmendmentRequestDao.java
@@ -1,5 +1,6 @@
package net.gepafin.tendermanagement.dao;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.criteria.CriteriaBuilder;
@@ -26,6 +27,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundExceptio
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
@@ -140,6 +142,12 @@ public class ApplicationAmendmentRequestDao {
@Autowired
private ApplicationDao applicationDao;
+ @Autowired
+ private EmailLogRepository emailLogRepository;
+
+ @Autowired
+ private EmailDao emailDao;
+
public ApplicationAmendmentRequestResponse getApplicationDataForAmendment(Long applicationEvaluationId) {
log.info("Fetching the application data for the Amendment process {}", applicationEvaluationId);
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluation(applicationEvaluationId);
@@ -301,6 +309,15 @@ public class ApplicationAmendmentRequestDao {
log.info("Application submitted successfully for amendment", applicationAmendmentRequestResponse);
if (Boolean.TRUE.equals(applicationAmendmentRequestResponse.getIsSendEmail())) {
emailNotificationDao.sendMailToNotifyBeneficiaryRegardingNewAmendment(applicationAmendmentRequestEntity);
+ EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
+ List responses = List.of(emailSendResponse);
+ if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
+ saveEmailSendResponse(emailSendResponse, applicationAmendmentRequestEntity);
+ applicationAmendmentRequestResponse.setEmailSendResponse(responses);
+ }
+ else{
+ applicationAmendmentRequestResponse.setEmailSendResponse(Collections.emptyList());
+ }
}
return applicationAmendmentRequestResponse;
}
@@ -361,6 +378,7 @@ public class ApplicationAmendmentRequestDao {
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(
applicationEvaluationEntity.getAssignedApplicationsEntity().getApplication(), protocolNumber,
userEntity.getHub().getId(),false);
+ protocolDao.saveProtocolEntity(protocolEntity);
applicationAmendmentRequestEntity.setProtocol(protocolEntity);
ApplicationAmendmentRequestEntity applicationAmendment = saveApplicationAmendmentRequestEntity(applicationAmendmentRequestEntity, null, VersionActionTypeEnum.INSERT);
log.info("Amendment request saved with ID={}", applicationAmendment.getId());
@@ -510,6 +528,7 @@ public class ApplicationAmendmentRequestDao {
Long hubId = applicationEntity.getHubId();
HubEntity hubEntity = hubService.valdateHub(hubId);
+ response.setEmailSendResponse(entity.getEmailSendResponse());
response.setId(entity.getId());
response.setApplicationId(entity.getApplicationId());
response.setApplicationEvaluationId(entity.getApplicationEvaluationEntity().getId());
@@ -651,9 +670,9 @@ public class ApplicationAmendmentRequestDao {
public ApplicationAmendmentRequestResponse getApplicationAmendmentRequestById(Long id) {
log.info("Fetching application amendment with ID: {}", id);
ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
- ApplicationAmendmentRequestResponse response = convertEntityToResponse(applicationAmendmentRequestEntity,true);
- log.info("Application Amendment fetched successfully by ID: {}", response);
- return response;
+ ApplicationAmendmentRequestResponse response = convertEntityToResponse(applicationAmendmentRequestEntity,true);
+ response.setEmailSendResponse(applicationAmendmentRequestEntity.getEmailSendResponse());
+ return response;
}
public List getAllApplicationAmendmentRequest(HttpServletRequest request, Long userId) {
@@ -1043,7 +1062,7 @@ public class ApplicationAmendmentRequestDao {
public ApplicationAmendmentRequestResponse closeAmendmentRequest(Long id, CloseAmendmentRequest closeAmendmentRequest) {
log.info("Closing application amendement with ID: {}", id);
- ApplicationAmendmentRequestEntity existingApplicationAmendment = validateApplicationAmendmentRequest(id);
+ ApplicationAmendmentRequestEntity existingApplicationAmendment = validatApplicationAmendmentRequestByListStatus(id,List.of(ApplicationAmendmentRequestEnum.AWAITING.getValue(),ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue()));
//cloned entity for old data and versioning
ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(existingApplicationAmendment);
List amendmentRequestList = applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(
@@ -1055,17 +1074,18 @@ public class ApplicationAmendmentRequestDao {
// Check if this is the last amendment being closed
boolean isLastRemaining = amendmentRequestList.stream()
.filter(amendment -> !amendment.getId().equals(id)) // Exclude the current amendment
- .allMatch(amendment -> amendment.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()));
+ .allMatch(amendment -> amendment.getStatus().equals(ApplicationAmendmentRequestEnum.CLOSE.getValue()) || amendment.getStatus().equals(ApplicationAmendmentRequestEnum.EXPIRED.getValue()));
+
- if (isLastRemaining) {
- log.info("The current amendment is the last remaining one to be closed.");
- applicationAmendmentRequestDao.calculateEndDateAndSuspensionDays(existingApplicationAmendment.getApplicationEvaluationEntity());
- }
setIfUpdated(existingApplicationAmendment::getInternalNote, existingApplicationAmendment::setInternalNote, closeAmendmentRequest.getInternalNote());
setIfUpdated(existingApplicationAmendment::getStatus, existingApplicationAmendment::setStatus, ApplicationAmendmentRequestEnum.CLOSE.getValue());
existingApplicationAmendment.setClosingDate(LocalDateTime.now());
ApplicationAmendmentRequestEntity updatedApplicationAmendment = saveApplicationAmendmentRequestEntity(existingApplicationAmendment, oldApplicationAmendmentEntity,
VersionActionTypeEnum.UPDATE);
+ if (isLastRemaining) {
+ log.info("The current amendment is the last remaining one to be closed.");
+ applicationAmendmentRequestDao.calculateEndDateAndSuspensionDaysOnExpirationOrClosing(existingApplicationAmendment.getApplicationEvaluationEntity());
+ }
ApplicationAmendmentRequestResponse response = convertEntityToResponse(updatedApplicationAmendment,false);
log.info("Updated amendment status to CLOSE for amendment ID: {}", id);
@@ -1095,6 +1115,8 @@ public class ApplicationAmendmentRequestDao {
existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getId());
AssignedApplicationsEntity oldAssignedApplicationData = Utils.getClonedEntityForData(assignedApplicationsEntity);
+ existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity().setStatus(AssignedApplicationEnum.OPEN.getValue());
+
assignedApplicationsEntity = assignedApplicationsRepository.save(existingApplicationAmendment.getApplicationEvaluationEntity().getAssignedApplicationsEntity());
log.info("Updated AssignedApplication status to OPEN for ID: {}", assignedApplicationsEntity.getId());
@@ -1121,16 +1143,18 @@ public class ApplicationAmendmentRequestDao {
return response;
}
-
public ApplicationAmendmentRequestResponse extendResponseDays(Long id, Long newResponseDays) {
log.info("Extending response days for Application Amendment ID: {}, Additional Days: {}", id, newResponseDays);
- ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validateApplicationAmendmentRequest(id);
+ ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = validatApplicationAmendmentRequestByStatus(id,ApplicationAmendmentRequestEnum.EXPIRED.getValue());
if (newResponseDays != null && newResponseDays > 0) {
- ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(applicationAmendmentRequestEntity);
+ ApplicationAmendmentRequestEntity oldApplicationAmendmentEntity = Utils.getClonedEntityForData(applicationAmendmentRequestEntity);
Long currentResponseDays = applicationAmendmentRequestEntity.getResponseDays() != null ? applicationAmendmentRequestEntity.getResponseDays() : 0L;
applicationAmendmentRequestEntity.setResponseDays(currentResponseDays + newResponseDays);
- applicationAmendmentRequestEntity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now().plusDays(applicationAmendmentRequestEntity.getResponseDays())));
+ applicationAmendmentRequestEntity.setEndDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now().plusDays(newResponseDays)));
+ applicationAmendmentRequestEntity.setStatus(ApplicationAmendmentRequestEnum.AWAITING.getValue());
+ applicationAmendmentRequestEntity.getApplicationEvaluationEntity().setStatus(ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
+ applicationAmendmentRequestEntity.getApplicationEvaluationEntity().getAssignedApplicationsEntity().getApplication().setStatus(ApplicationStatusTypeEnum.SOCCORSO.getValue());
applicationAmendmentRequestRepository.save(applicationAmendmentRequestEntity);
/** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
@@ -1187,7 +1211,7 @@ public class ApplicationAmendmentRequestDao {
return response;
}
- public void sendReminderEmail(Long amendmentId) {
+ public EmailReminderResponse sendReminderEmail(Long amendmentId) {
log.info("Initiating reminder email process for Amendment ID: {}", amendmentId);
ApplicationAmendmentRequestEntity amendment = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(amendmentId)
.orElseThrow(() -> { log.error("Amendment not found with ID: {}", amendmentId);
@@ -1195,6 +1219,7 @@ public class ApplicationAmendmentRequestDao {
});
Optional entityOptional = applicationEvaluationRepository.findByIdAndIsDeletedFalse(amendment.getApplicationEvaluationEntity().getId());
+ EmailReminderResponse emailReminderResponse = new EmailReminderResponse();
if (entityOptional.isPresent()) {
ApplicationEntity applicationEntity = applicationService.validateApplication(entityOptional.get().getApplicationId());
UserEntity beneficiaryUser = userService.validateUser(applicationEntity.getUserId());
@@ -1208,12 +1233,22 @@ public class ApplicationAmendmentRequestDao {
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, beneficiaryUser.getId(), email,
beneficiaryUser.getId(), applicationEntity.getId(), amendment.getId(), applicationEntity.getCall().getId());
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email), emailLogRequest);
+ EmailSendResponse emailSendResponse = emailDao.buildEmailSendResponseFromRequest(request);
+ List responses = List.of(emailSendResponse);
+ if (!Boolean.TRUE.equals(emailSendResponse.getIsEmailSend())){
+ emailReminderResponse.setEmailSendResponse(responses);
+ saveEmailSendResponse(emailSendResponse, amendment);
+ }
+ else{
+ emailReminderResponse.setEmailSendResponse(Collections.emptyList());
+ }
log.info("Reminder email sent successfully for Amendment ID: {}", amendmentId);
} else {
log.warn("Beneficiary email not found or isEmail flag is false for Amendment ID: {}", amendmentId);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.BENEFICIARY_EMAIL_NOT_FOUND_MSG));
}
}
+ return emailReminderResponse;
}
private String prepareSubject(SystemEmailTemplateResponse template, ApplicationAmendmentRequestEntity amendment, UserEntity beneficiary) {
@@ -1243,29 +1278,26 @@ public class ApplicationAmendmentRequestDao {
return Utils.replacePlaceholders(template.getHtmlContent(), bodyPlaceholders);
}
- public ApplicationEvaluationEntity calculateEndDateAndSuspensionDays(ApplicationEvaluationEntity applicationEvaluationEntity){
- log.info("Calculating end date and suspension days for Application Evaluation ID: {}", applicationEvaluationEntity.getId());
- LocalDateTime currentDate=DateTimeUtil.DateServerToUTC(LocalDateTime.now());
- LocalDateTime endDate=currentDate.plusDays(applicationEvaluationEntity.getRemainingDays());
- Long suspendedDays = ChronoUnit.DAYS.between(applicationEvaluationEntity.getStopDateTime(), currentDate);
-
- ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
- applicationEvaluationEntity.setEndDate(endDate);
- if(applicationEvaluationEntity.getSuspendedDays() == null) {
- applicationEvaluationEntity.setSuspendedDays(0L);
- }
- applicationEvaluationEntity.setSuspendedDays(applicationEvaluationEntity.getSuspendedDays()+suspendedDays);
- log.debug("Updated suspended days: {}", applicationEvaluationEntity.getSuspendedDays());
- ApplicationEvaluationEntity applicationEvaluation = applicationEvaluationRepository.save(applicationEvaluationEntity);
-
- log.info("Application Evaluation updated successfully. ID: {}", applicationEvaluation.getId());
- /** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
- loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluationEntity).newData(applicationEvaluation).build());
-
- return applicationEvaluation;
-
-
- }
+// public ApplicationEvaluationEntity calculateEndDateAndSuspensionDays(ApplicationEvaluationEntity applicationEvaluationEntity){
+// LocalDateTime currentDate=DateTimeUtil.DateServerToUTC(LocalDateTime.now());
+// LocalDateTime endDate=currentDate.plusDays(applicationEvaluationEntity.getRemainingDays());
+// Long suspendedDays = ChronoUnit.DAYS.between(applicationEvaluationEntity.getStopDateTime(), currentDate);
+//
+// ApplicationEvaluationEntity oldApplicationEvaluationEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
+// applicationEvaluationEntity.setEndDate(endDate);
+// if(applicationEvaluationEntity.getSuspendedDays() == null) {
+// applicationEvaluationEntity.setSuspendedDays(0L);
+// }
+// applicationEvaluationEntity.setSuspendedDays(applicationEvaluationEntity.getSuspendedDays()+suspendedDays);
+// ApplicationEvaluationEntity applicationEvaluation = applicationEvaluationRepository.save(applicationEvaluationEntity);
+//
+// /** This code is responsible for adding a version history log for the "Update Application Amendment" operation. **/
+// loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEvaluationEntity).newData(applicationEvaluation).build());
+//
+// return applicationEvaluation;
+//
+//
+// }
private GetAllAmendmentResponseBean initializeGetAllBasicResponse(ApplicationAmendmentRequestEntity entity) {
GetAllAmendmentResponseBean response = new GetAllAmendmentResponseBean();
@@ -1572,8 +1604,111 @@ public class ApplicationAmendmentRequestDao {
applicationAmendmentRequestViewResponse.setExpirationDate(applicationAmendmentRequestView.getExpirationDate());
applicationAmendmentRequestViewResponse.setAssigendUserName(applicationAmendmentRequestView.getAssigendUserName());
applicationAmendmentRequestViewResponse.setStatus(applicationAmendmentRequestView.getStatus());
+ applicationAmendmentRequestViewResponse.setEmailSendResponse(applicationAmendmentRequestView.getEmailSendResponse());
return applicationAmendmentRequestViewResponse;
}
+ public ApplicationEvaluationEntity calculateEndDateAndSuspensionDaysOnExpirationOrClosing
+ (ApplicationEvaluationEntity applicationEvaluationEntity) {
+
+ // Fetch all linked amendments
+ List amendments =
+ applicationAmendmentRequestRepository.findAllByApplicationEvaluationIdAndIsDeletedFalse(applicationEvaluationEntity.getId());
+
+ // Recalculate suspension
+ long suspendedDays = calculateSuspendedDays(amendments);
+
+ // Update end date and save
+
+ ApplicationEvaluationEntity oldEntity = Utils.getClonedEntityForData(applicationEvaluationEntity);
+ HubEntity hub = hubService.valdateHub(applicationEvaluationEntity.getAssignedApplicationsEntity().getApplication().getHubId());
+ Long initialDays = (hub != null) ? hub.getEvaluationExpirationDays() : 30L;
+ LocalDateTime endDate = applicationEvaluationEntity.getStartDate().plusDays(suspendedDays+initialDays);
+ applicationEvaluationEntity.setEndDate(endDate);
+ applicationEvaluationEntity.setSuspendedDays(suspendedDays);
+ ApplicationEvaluationEntity updated = applicationEvaluationRepository.save(applicationEvaluationEntity);
+
+ loggingUtil.addVersionHistory(VersionHistoryRequest.builder()
+ .request(request)
+ .actionType(VersionActionTypeEnum.UPDATE)
+ .oldData(oldEntity)
+ .newData(updated)
+ .build());
+
+ return updated;
+ }
+
+ public long calculateSuspendedDays(List amendments) {
+ List> periods = amendments.stream()
+ .filter(amendmentRequest -> amendmentRequest.getStartDate() != null)
+ .map(amendmentRequest -> {
+ LocalDateTime start = amendmentRequest.getStartDate();
+ LocalDateTime end;
+
+ String status = amendmentRequest.getStatus();
+ if (Boolean.TRUE.equals(ApplicationAmendmentRequestEnum.CLOSE.getValue().equals(status)) && amendmentRequest.getClosingDate() != null) {
+ end = amendmentRequest.getClosingDate();
+ } else if (Boolean.TRUE.equals(ApplicationAmendmentRequestEnum.EXPIRED.getValue().equals(status)) && amendmentRequest.getEndDate() != null) {
+ end = amendmentRequest.getStartDate().plusDays(amendmentRequest.getResponseDays());
+ }else {
+ end= amendmentRequest.getEndDate();
+ }
+
+ return Pair.of(start, end);
+ })
+ .filter(Objects::nonNull)
+ .sorted(Comparator.comparing(Pair::getLeft))
+ .collect(Collectors.toList());
+
+ long totalDays = 0;
+ LocalDateTime currentStart = null;
+ LocalDateTime currentEnd = null;
+
+ for (Pair period : periods) {
+ if (currentStart == null) {
+ currentStart = period.getLeft();
+ currentEnd = period.getRight();
+ } else if (!period.getLeft().isAfter(currentEnd)) {
+ // Merge overlapping/touching periods
+ currentEnd = currentEnd.isAfter(period.getRight()) ? currentEnd : period.getRight();
+ } else {
+ // Non-overlapping: count previous period
+ totalDays += ChronoUnit.DAYS.between(currentStart.toLocalDate(), currentEnd.toLocalDate());
+ currentStart = period.getLeft();
+ currentEnd = period.getRight();
+ }
+ }
+
+ if (currentStart != null && currentEnd != null) {
+ totalDays += ChronoUnit.DAYS.between(currentStart.toLocalDate(), currentEnd.toLocalDate());
+ }
+
+ return totalDays;
+ }
+
+
+
+ public ApplicationAmendmentRequestEntity validatApplicationAmendmentRequestByStatus(Long id,String status) {
+ ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalseAndStatus(id, status);
+ if (applicationAmendmentRequestEntity == null) {
+ throw new ResourceNotFoundException(Status.NOT_FOUND,
+ Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG));
+ }
+ return applicationAmendmentRequestEntity;
+ }
+ private void saveEmailSendResponse(EmailSendResponse newResponses, ApplicationAmendmentRequestEntity amendment) {
+ List mergedResponses = Utils.mergeEmailSendResponses(amendment.getEmailSendResponse(), newResponses);
+
+ amendment.setEmailSendResponse(mergedResponses);
+ applicationAmendmentRequestRepository.save(amendment);
+ }
+ public ApplicationAmendmentRequestEntity validatApplicationAmendmentRequestByListStatus(Long id,List status) {
+ ApplicationAmendmentRequestEntity applicationAmendmentRequestEntity = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalseAndStatusIn(id, status);
+ if (applicationAmendmentRequestEntity == null) {
+ throw new ResourceNotFoundException(Status.NOT_FOUND,
+ Translator.toLocale(GepafinConstant.APPLICATION_AMENDMENT_NOT_FOUND_MSG));
+ }
+ return applicationAmendmentRequestEntity;
+ }
}
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java
index f54f26cc..c45171e8 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java
@@ -1,10 +1,15 @@
package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.itextpdf.text.BaseColor;
+import com.itextpdf.text.Font;
+import com.itextpdf.text.FontFactory;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.*;
+import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
@@ -23,15 +28,14 @@ import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
import net.gepafin.tendermanagement.service.UserService;
-import net.gepafin.tendermanagement.util.DateTimeUtil;
-import net.gepafin.tendermanagement.util.FieldValidator;
-import net.gepafin.tendermanagement.util.LoggingUtil;
-import net.gepafin.tendermanagement.util.Utils;
-import net.gepafin.tendermanagement.util.Validator;
+import net.gepafin.tendermanagement.util.*;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
+import org.apache.commons.csv.CSVFormat;
+import org.apache.commons.csv.CSVPrinter;
+import org.apache.commons.lang3.StringUtils;
import org.h2.util.IOUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -49,17 +53,17 @@ import jakarta.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.lang.reflect.Method;
import java.math.BigDecimal;
+
import java.sql.Timestamp;
import java.text.MessageFormat;
-import java.text.NumberFormat;
-import java.text.ParseException;
+import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
-import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
-import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -69,7 +73,6 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.apache.commons.lang3.StringUtils.isEmpty;
-import static org.hibernate.validator.internal.engine.messageinterpolation.el.RootResolver.FORMATTER;
@Component
public class ApplicationDao {
@@ -133,6 +136,9 @@ public class ApplicationDao {
@Value("${call.id}")
private String callId;
+ @Value("${sviluppumbriaUuid}")
+ private String sviluppumbriaUuid;
+
@Autowired
private AmazonS3Service amazonS3Service;
@@ -196,6 +202,16 @@ public class ApplicationDao {
@Autowired
private ApplicationViewRepository applicationViewRepository;
+ @Autowired
+ private ApplicationFormViewRepository applicationFormViewRepository;
+
+ @Autowired
+ private FormRepository formRepository;
+
+ @Autowired
+ private ApplicationEvaluationDao applicationEvaluationDao;
+
+ public final Random random = new Random();
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
log.info("Starting createApplication: formId={}, applicationId={}", formId, applicationId);
@@ -952,16 +968,20 @@ public class ApplicationDao {
}
}
+ public String generateRandomFiveDigitNumber() {
+ int number = 10000 + random.nextInt(90000); // Generates a number from 10000 to 99999
+ return String.valueOf(number);
+ }
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
log.info("Updating status for Application id : " + applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
- checkCallEndDate(applicationEntity.getCall());
+
log.info("Call end date verified successfully | callId: {}", applicationEntity.getCall().getId());
//cloned entity for old application data
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(applicationEntity);
-
+ HubEntity hub=hubService.valdateHub(applicationEntity.getHubId());
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
@@ -973,11 +993,25 @@ public class ApplicationDao {
log.warn("Requested status is the same as current status | applicationId: {}, status: {}", applicationId, status);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_IN_PREVIOUS_STATUS));
}
+
+ if (status.equals(ApplicationStatusTypeEnum.APPOINTMENT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.NDG.getValue()))){
+ String appointmentId = generateRandomFiveDigitNumber();
+ applicationEntity.setAppointmentId(appointmentId);
+ applicationEntity.setStatus(ApplicationStatusTypeEnum.APPOINTMENT.getValue());
+ }
+
if (status.equals(ApplicationStatusTypeEnum.SUBMIT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
+ CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
+
// callService.validatePublishedCall(applicationEntity.getCall().getId(), userEntity.getHub().getId());
+ checkCallEndDate(applicationEntity.getCall());
Long protocolNumber = protocolDao.getProtocolNumber(userEntity.getHub());
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true);
+ protocolDao.saveProtocolEntity(protocolEntity);
applicationEntity.setProtocol(protocolEntity);
+ if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(sviluppumbriaUuid))) {
+ protocolEntity = protocolDao.createExternalProtocol(applicationEntity, company, protocolEntity);
+ }
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(protocolEntity.getCreatedDate());
applicationEntity = applicationRepository.save(applicationEntity);
@@ -988,16 +1022,18 @@ public class ApplicationDao {
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEntity).newData(applicationEntity).build());
- sendMailToUserAndCompany(userEntity, applicationEntity);
+ sendMailToUserAndCompany(userEntity, applicationEntity,company);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
applicationEntity.setStatus(status.getValue());
log.info("Status updated to SUBMIT for applicationId: " + applicationId);
}
if (status.equals(ApplicationStatusTypeEnum.DRAFT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.AWAITING.getValue()))) {
+ checkCallEndDate(applicationEntity.getCall());
applicationEntity.setStatus(status.getValue());
log.info("Status updated to DRAFT for applicationId: " + applicationId);
}
if (status.equals(ApplicationStatusTypeEnum.AWAITING) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
+ checkCallEndDate(applicationEntity.getCall());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository.findByApplicationIdAndStatus(applicationId,
ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
deleteSignedDocumentFromS3(applicationSignedDocument);
@@ -1099,10 +1135,9 @@ public class ApplicationDao {
}
}
- private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity) {
+ private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity,CompanyEntity company) {
log.info("Preparing to send submission email | applicationId: {}, userId: {}", applicationEntity.getId(), userEntity.getId());
CallEntity call =applicationEntity.getCall();
- CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId());
ProtocolEntity protocol= applicationEntity.getProtocol();
HubEntity hub = hubService.valdateHub(applicationEntity.getHubId());
@@ -1130,7 +1165,7 @@ public class ApplicationDao {
if (userEntity.getBeneficiary() != null) {
emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY);
email = userEntity.getBeneficiary().getEmail();
- emailLogRequest.setUserId(userEntity.getBeneficiary().getId());
+ emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId());
}
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogRequest);
List recipientEmails = new ArrayList<>();
@@ -1179,24 +1214,6 @@ public class ApplicationDao {
EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId());
-// mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
-// mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
-// mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
-// if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(defaultHubUuid))) {
-// if (validator.isProductionProfileActivated()) {
-// emailLogRequest.setRecipientEmails(carloEmail);
-//// mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
-// emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(carloEmail),emailLogRequest);
-// }
-// List listDefaultSystemReceiverEmail = Arrays.stream(defaultSystemReceiverEmail.split(","))
-// .map(String::trim)
-// .filter(email -> !email.isEmpty())
-// .toList();
-//
-// emailLogRequest.setRecipientEmails(defaultSystemReceiverEmail);
-// emailNotificationDao.sendMail(hub.getId(), subject, body, listDefaultSystemReceiverEmail, emailLogRequest);
-// }
-
List hubEmails = Arrays.stream(hub.getEmail().split(","))
.map(String::trim)
.filter(email -> !email.isEmpty())
@@ -1225,6 +1242,12 @@ public class ApplicationDao {
log.info("Existing active signed document found and will be deleted | applicationId: {}, fileName: {}", applicationId, applicationSignedDocument.getFileName());
deleteSignedDocumentFromS3(applicationSignedDocument);
}
+ String hash ="";
+ try {
+ hash = FileHashUtil.calculateSHA256(file.getInputStream());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = uploadFileOnAmazonS3ForUserSignedDocument(file, applicationEntity.getCall().getId(), applicationId);
log.info("File uploaded to S3 successfully | applicationId: {}", applicationId);
applicationSignedDocument = new ApplicationSignedDocumentEntity();
@@ -1232,6 +1255,7 @@ public class ApplicationDao {
applicationSignedDocument.setFileName(uploadFileOnAmazonS3.getFileName());
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
+ applicationSignedDocument.setFileHash(hash);
applicationSignedDocument = applicationSignedDocumentRepository.save(applicationSignedDocument);
/** This code is responsible for adding a version history log for the "assign application document" operation. **/
@@ -1307,6 +1331,7 @@ public class ApplicationDao {
.setStatus(ApplicationSignedDocumentStatusEnum.valueOf(applicationSignedDocument.getStatus()));
applicationSignedDocumentResponse.setCreatedDate(applicationSignedDocument.getCreatedDate());
applicationSignedDocumentResponse.setUpdatedDate(applicationSignedDocument.getUpdatedDate());
+ applicationSignedDocumentResponse.setFileHash(applicationSignedDocument.getFileHash());
return applicationSignedDocumentResponse;
}
@@ -1885,4 +1910,429 @@ public class ApplicationDao {
responseBean.setDateRejected(applicationView.getDateRejected());
return responseBean;
}
+
+ public List getApplicationFormData(Long callId) {
+ List applicationFormViews=new ArrayList<>();
+
+ applicationFormViews= applicationFormViewRepository.findByCallId(callId);
+
+ return applicationFormViews;
+ }
+
+ private List getStaticGetterMethods() {
+ List excluded = Arrays.asList(
+ GepafinConstant.GET_FIELD_TYPE,GepafinConstant.GET_APPLICATION_FORM_ID,GepafinConstant.GET_ID,GepafinConstant.GET_CLASS,GepafinConstant.GET_FORM_ID,GepafinConstant.GET_FIELD_ID,GepafinConstant.GET_FIELD_LABEL,GepafinConstant.GET_FIELD_VALUE,GepafinConstant.GET_REPORT_HEADER,GepafinConstant.GET_REPORT_ENABLE
+ );
+
+ Method applicationIdMethod = null;
+
+ List methods = new ArrayList<>();
+
+ for (Method m : ApplicationFormView.class.getMethods()) {
+ if (m.getName().equals(GepafinConstant.GET_APPLICATION_ID)) {
+ applicationIdMethod = m;
+ } else if (m.getName().startsWith(GepafinConstant.GET) && m.getParameterCount() == 0 && !excluded.contains(m.getName())) {
+ methods.add(m);
+ }
+ }
+
+ methods.sort(Comparator.comparing(Method::getName)); // Sort remaining
+
+ if (applicationIdMethod != null) {
+ methods.add(0, applicationIdMethod); // Add it to the beginning
+ }
+
+ return methods;
+
+ }
+
+ private String methodToHeader(Method method) {
+ String name = method.getName().substring(3); // strip "get"
+ return Arrays.stream(name.split("(?=[A-Z])"))
+ .map(String::toLowerCase)
+ .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
+ .collect(Collectors.joining(" "));
+ }
+
+ private String invokeGetter(ApplicationFormView view, Method method) {
+ try {
+ Object value = method.invoke(view);
+ if (value == null) return "";
+
+ String stringValue;
+
+ if (value instanceof LocalDate) {
+ stringValue = ((LocalDate) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+ } else if (value instanceof LocalDateTime) {
+ stringValue = ((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+ } else if (value instanceof Date) {
+ stringValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
+ } else {
+ stringValue = value.toString();
+ }
+
+ // Wrap it in ="..." to make Excel treat it as a literal string
+ return "=\"" + stringValue.replace("\"", "\"\"") + "\"";
+
+ } catch (Exception e) {
+ return "";
+ }
+ }
+
+
+ public byte[] exportCsv(Long callId) {
+
+ List results = getApplicationFormData(callId);
+
+
+ Map appInfo = new HashMap<>();
+ Map> appFieldValues = new LinkedHashMap<>();
+ Set tableFieldIds = new HashSet<>();
+ Map fieldIdToLabel = new LinkedHashMap<>();
+
+ for (ApplicationFormView row : results) {
+ appInfo.putIfAbsent(row.getApplicationId(), row);
+ String label=row.getReportHeader();
+ if(Boolean.TRUE.equals(StringUtils.isEmpty(label))){
+ label=row.getFieldLabel();
+ }
+ fieldIdToLabel.putIfAbsent(row.getFieldId(), label);
+
+ if (GepafinConstant.TABLE.equalsIgnoreCase(row.getFieldType())) {
+ tableFieldIds.add(row.getFieldId());
+ continue;
+ }
+
+ String value = Optional.ofNullable(row.getFieldValue())
+ .map(v -> v.startsWith("\"") && v.endsWith("\"") ? v.substring(1, v.length() - 1) : v)
+ .orElse("");
+
+ appFieldValues
+ .computeIfAbsent(row.getApplicationId(), k -> new LinkedHashMap<>())
+ .merge(row.getFieldId(), value, (v1, v2) -> v1.equals(v2) ? v1 : String.join(", ", v1, v2));
+ }
+
+ Map> tableHeadersByFieldId = new LinkedHashMap<>();
+ Map> tableDataByApp = new HashMap<>();
+ prepareTableFieldData(results, tableFieldIds, tableHeadersByFieldId, tableDataByApp);
+
+ // Final header construction
+ List staticMethods = getStaticGetterMethods();
+ List staticHeaders = staticMethods.stream().map(this::methodToHeader).toList();
+
+ List dynamicHeaders = new ArrayList<>();
+ for (String fieldId : fieldIdToLabel.keySet()) {
+ if (tableHeadersByFieldId.containsKey(fieldId)) {
+ dynamicHeaders.addAll(tableHeadersByFieldId.get(fieldId));
+ } else {
+ dynamicHeaders.add(fieldIdToLabel.get(fieldId));
+ }
+ }
+
+ List allHeaders = new ArrayList<>(staticHeaders);
+ allHeaders.addAll(dynamicHeaders);
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try (CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(out), CSVFormat.DEFAULT.withHeader(allHeaders.toArray(new String[0])))) {
+ for (Long appId : appFieldValues.keySet()) {
+ ApplicationFormView appRow = appInfo.get(appId);
+ Map flatFieldVals = appFieldValues.get(appId);
+ Map tableVals = tableDataByApp.getOrDefault(appId, Collections.emptyMap());
+
+ List row = new ArrayList<>();
+ for (Method method : staticMethods) {
+ row.add(invokeGetter(appRow, method));
+ }
+
+ for (String fieldId : fieldIdToLabel.keySet()) {
+ if (tableHeadersByFieldId.containsKey(fieldId)) {
+ for (String header : tableHeadersByFieldId.get(fieldId)) {
+ row.add(tableVals.getOrDefault(header, ""));
+ }
+ } else {
+ row.add(flatFieldVals.getOrDefault(fieldId, ""));
+ }
+ }
+
+ printer.printRecord(row);
+ }
+
+ } catch (IOException e) {
+ throw new RuntimeException("CSV generation failed", e);
+ }
+
+ return out.toByteArray();
+ }
+ private Map extractTableData(String fieldType,
+ ContentResponseBean content, String fieldValue) {
+
+ if (content == null) return Map.of();
+
+ Map result = new LinkedHashMap<>();
+
+ List