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