Resolve Conflicts
This commit is contained in:
@@ -306,7 +306,7 @@ public class ApplicationAmendmentRequestDao {
|
||||
ApplicationAmendmentRequestEntity applicationAmendment = saveApplicationAmendmentRequestEntity(applicationAmendmentRequestEntity, null, VersionActionTypeEnum.INSERT);
|
||||
String evaluationStatusType = applicationEvaluationEntity.getStatus();
|
||||
if (Boolean.FALSE.equals(evaluationStatusType.equals((ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue())))){
|
||||
applicationEvaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
|
||||
// applicationEvaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
|
||||
|
||||
//Set Status
|
||||
applicationEvaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
|
||||
|
||||
@@ -47,6 +47,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.text.MessageFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
@@ -172,6 +173,12 @@ public class ApplicationDao {
|
||||
@Autowired
|
||||
private RoleRepository roleRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestRepository applicationAmendmentRequestRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
|
||||
FormEntity formEntity = formService.validateForm(formId);
|
||||
// callService.validatePublishedCall(formEntity.getCall().getId());
|
||||
@@ -213,7 +220,7 @@ public class ApplicationDao {
|
||||
}
|
||||
|
||||
public ApplicationEntity createApplicationEntity(UserEntity user, CallEntity call, UserWithCompanyEntity userWithCompany) {
|
||||
validateDelegation(user,userWithCompany);
|
||||
// validateDelegation(user,userWithCompany);
|
||||
ApplicationEntity entity = new ApplicationEntity();
|
||||
entity.setUserId(user.getId());
|
||||
entity.setCompanyId(userWithCompany.getCompanyId());
|
||||
@@ -289,7 +296,12 @@ public class ApplicationDao {
|
||||
log.info("Deleting application with ID: {}", id);
|
||||
|
||||
ApplicationEntity applicationEntity= validateApplication(id);
|
||||
|
||||
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.DRAFT.getValue().equals(applicationEntity.getStatus()))) {
|
||||
throw new CustomValidationException(
|
||||
Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS)
|
||||
);
|
||||
}
|
||||
ApplicationEntity oldApplicationDataEntity = Utils.getClonedEntityForData(applicationEntity);
|
||||
|
||||
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
|
||||
@@ -412,6 +424,10 @@ public class ApplicationDao {
|
||||
if(applicationEntity.getProtocol() != null) {
|
||||
responseBean.setProtocolNumber(applicationEntity.getProtocol().getProtocolNumber());
|
||||
}
|
||||
responseBean.setAmountAccepted(applicationEntity.getAmountAccepted());
|
||||
responseBean.setAmountRequested(applicationEntity.getAmountRequested());
|
||||
responseBean.setDateAccepted(applicationEntity.getDateAccepted());
|
||||
responseBean.setDateRejected(applicationEntity.getDateRejected());
|
||||
return responseBean;
|
||||
}
|
||||
|
||||
@@ -431,6 +447,10 @@ public class ApplicationDao {
|
||||
response.setCallId(entity.getCall().getId());
|
||||
response.setCreatedDate(entity.getCreatedDate());
|
||||
response.setUpdatedDate(entity.getUpdatedDate());
|
||||
response.setAmountAccepted(entity.getAmountAccepted());
|
||||
response.setAmountRequested(entity.getAmountRequested());
|
||||
response.setDateAccepted(entity.getDateAccepted());
|
||||
response.setDateRejected(entity.getDateRejected());
|
||||
if(entity.getProtocol() != null) {
|
||||
response.setProtocolNumber(entity.getProtocol().getProtocolNumber());
|
||||
}
|
||||
@@ -469,6 +489,30 @@ public class ApplicationDao {
|
||||
List<Long> newDocumentIds = validateFileUploadDocuments(applicationFormFieldRequestBean, formEntity);
|
||||
validateFileUploadDocuments(applicationFormFieldRequestBean, formEntity);
|
||||
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
|
||||
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
|
||||
|
||||
contentResponseBeans.stream()
|
||||
.filter(content -> "numberinput".equals(content.getName()))
|
||||
.map(ContentResponseBean::getSettings)
|
||||
.flatMap(List::stream)
|
||||
.filter(setting -> "isRequestedAmount".equals(setting.getName()) && Boolean.TRUE.equals(setting.getValue()))
|
||||
.findFirst()
|
||||
.ifPresent(setting -> {
|
||||
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
|
||||
if(fieldValue!=null) {
|
||||
if (fieldValue instanceof String) {
|
||||
try {
|
||||
BigDecimal amountRequested = new BigDecimal((String) fieldValue);
|
||||
applicationFormEntity.getApplication().setAmountRequested(amountRequested);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException("Field value is not a valid number: " + fieldValue, e);
|
||||
}
|
||||
} else {
|
||||
throw new IllegalArgumentException("Field value is not a String: " + fieldValue);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
ApplicationFormFieldEntity oldApplicationFormFieldData = null;
|
||||
|
||||
@@ -800,6 +844,10 @@ public class ApplicationDao {
|
||||
applicationGetResponseBean.setCallId(applicationEntity.getCall().getId());
|
||||
applicationGetResponseBean.setCallTitle(applicationEntity.getCall().getName());
|
||||
applicationGetResponseBean.setCompanyId(applicationEntity.getCompanyId());
|
||||
applicationGetResponseBean.setAmountAccepted(applicationEntity.getAmountAccepted());
|
||||
applicationGetResponseBean.setAmountRequested(applicationEntity.getAmountRequested());
|
||||
applicationGetResponseBean.setDateAccepted(applicationEntity.getDateAccepted());
|
||||
applicationGetResponseBean.setDateRejected(applicationEntity.getDateRejected());
|
||||
if(applicationEntity.getProtocol() != null) {
|
||||
applicationGetResponseBean.setProtocolNumber(applicationEntity.getProtocol().getProtocolNumber());
|
||||
}
|
||||
@@ -859,7 +907,7 @@ public class ApplicationDao {
|
||||
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true);
|
||||
applicationEntity.setProtocol(protocolEntity);
|
||||
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
|
||||
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
applicationEntity.setSubmissionDate(protocolEntity.getCreatedDate());
|
||||
applicationEntity = applicationRepository.save(applicationEntity);
|
||||
Map<String ,String> placeHolders=notificationDao.sendNotificationToBeneficiary(applicationEntity,NotificationTypeEnum.APPLICATION_SUBMISSION);
|
||||
notificationDao.sendNotificationToSuperUser(applicationEntity,placeHolders,NotificationTypeEnum.APPLICATION_SUBMISSION);
|
||||
@@ -975,7 +1023,8 @@ public class ApplicationDao {
|
||||
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity) {
|
||||
CallEntity call =applicationEntity.getCall();
|
||||
CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
|
||||
ProtocolEntity protocol = applicationEntity.getProtocol();
|
||||
UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId());
|
||||
ProtocolEntity protocol= applicationEntity.getProtocol();
|
||||
HubEntity hub = hubService.valdateHub(applicationEntity.getHubId());
|
||||
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
|
||||
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_USER_AND_COMPANY,
|
||||
@@ -1006,8 +1055,8 @@ public class ApplicationDao {
|
||||
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogRequest);
|
||||
List<String> recipientEmails = new ArrayList<>();
|
||||
// recipientEmails.add(email);
|
||||
String companyEmail = company.getEmail();
|
||||
String contactEmail = company.getContactEmail();
|
||||
String companyEmail = userWithCompany.getEmail();
|
||||
String contactEmail = userWithCompany.getContactEmail();
|
||||
|
||||
if (companyEmail != null && !companyEmail.isEmpty()) {
|
||||
recipientEmails.add(companyEmail);
|
||||
@@ -1225,90 +1274,121 @@ public class ApplicationDao {
|
||||
}
|
||||
|
||||
public byte[] downloadApplicationDocumentsAsZip(HttpServletRequest request, Long applicationId) {
|
||||
|
||||
ApplicationEntity applicationEntity = validateApplication(applicationId);
|
||||
validateAssignedUser(request, applicationId);
|
||||
|
||||
Set<Long> documentIds = extractDocumentIdsFromApplicationForms(applicationId);
|
||||
List<DocumentEntity> documents = documentRepository.findAllByIdInAndIsDeletedFalse(documentIds);
|
||||
|
||||
ApplicationSignedDocumentEntity signedDocument = applicationSignedDocumentRepository
|
||||
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
|
||||
if (documents.isEmpty() && signedDocument == null) {
|
||||
ApplicationSignedDocumentEntity signedDocument = applicationSignedDocumentRepository.findByApplicationIdAndStatus(applicationId,
|
||||
ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
|
||||
List<DocumentEntity> amendmentDocuments = fetchAmendmentDocuments(applicationId);
|
||||
List<DocumentEntity> evaluationDocuments = fetchEvaluationDocuments(applicationId);
|
||||
if (documents.isEmpty() && signedDocument == null && amendmentDocuments.isEmpty() && evaluationDocuments.isEmpty()) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND));
|
||||
}
|
||||
return createZipWithDocuments(applicationEntity, documents, signedDocument, applicationId);
|
||||
return createZipWithDocuments(applicationEntity, documents, signedDocument, amendmentDocuments, evaluationDocuments, applicationId);
|
||||
}
|
||||
|
||||
private void validateAssignedUser(HttpServletRequest request, Long applicationId) {
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository
|
||||
.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
|
||||
|
||||
AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
|
||||
if (assignedApplications != null) {
|
||||
validator.validatePreInstructor(request, assignedApplications.getUserId());
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> extractDocumentIdsFromApplicationForms(Long applicationId) {
|
||||
|
||||
Set<Long> documentIds = new HashSet<>();
|
||||
List<ApplicationFormEntity> applicationForms = applicationFormRepository.findByApplicationId(applicationId);
|
||||
|
||||
applicationForms.forEach(applicationForm -> {
|
||||
FormEntity formEntity = applicationForm.getForm();
|
||||
if (formEntity != null) {
|
||||
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
|
||||
contentResponseBeans.stream()
|
||||
.filter(content -> "fileupload".equals(content.getName()))
|
||||
.forEach(content -> {
|
||||
Optional<ApplicationFormFieldEntity> formField = applicationFormFieldRepository
|
||||
.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
|
||||
content.getId(), applicationForm.getId(), applicationId);
|
||||
formField.ifPresent(field -> {
|
||||
if (field.getFieldValue() != null) {
|
||||
Arrays.stream(field.getFieldValue().split(","))
|
||||
.map(String::trim)
|
||||
.map(Long::valueOf)
|
||||
.forEach(documentIds::add);
|
||||
}
|
||||
});
|
||||
});
|
||||
contentResponseBeans.stream().filter(content -> "fileupload".equals(content.getName())).forEach(content -> {
|
||||
Optional<ApplicationFormFieldEntity> formField = applicationFormFieldRepository.findByFieldIdAndApplicationFormIdAndApplicationFormApplicationId(
|
||||
content.getId(), applicationForm.getId(), applicationId);
|
||||
formField.ifPresent(field -> {
|
||||
if (field.getFieldValue() != null) {
|
||||
Arrays.stream(field.getFieldValue().split(",")).map(String::trim).map(Long::valueOf).forEach(documentIds::add);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
return documentIds;
|
||||
}
|
||||
|
||||
private void addDocumentToZip(ZipOutputStream zos, String s3Folder, String filePath, String fileName) {
|
||||
private List<DocumentEntity> fetchAmendmentDocuments(Long 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) {
|
||||
|
||||
Optional<ApplicationEvaluationEntity> evaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationId);
|
||||
if (evaluationEntity.isPresent()) {
|
||||
Long evaluationId = evaluationEntity.get().getId();
|
||||
return documentRepository.findBySourceIdInAndSourceAndIsDeletedFalse(Collections.singleton(evaluationId), DocumentSourceTypeEnum.EVALUATION.getValue());
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
private String fetchProtocolNumberForAmendment(Long amendmentRequestId) {
|
||||
|
||||
ApplicationAmendmentRequestEntity amendmentRequest = applicationAmendmentRequestRepository.findByIdAndIsDeletedFalse(amendmentRequestId).orElse(null);
|
||||
if (amendmentRequest != null && amendmentRequest.getProtocol() != null) {
|
||||
return amendmentRequest.getProtocol().getProtocolNumber().toString();
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
private void addDocumentToZip(ZipOutputStream zos, String s3Folder, String filePath, String fullPath) {
|
||||
|
||||
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, filePath)) {
|
||||
zos.putNextEntry(new ZipEntry(fileName));
|
||||
zos.putNextEntry(new ZipEntry(fullPath));
|
||||
IOUtils.copy(fileInputStream, zos);
|
||||
zos.closeEntry();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error downloading or adding document to ZIP: " + fileName, e);
|
||||
throw new RuntimeException("Error downloading or adding document to ZIP: " + fullPath, e);
|
||||
}
|
||||
}
|
||||
private byte[] createZipWithDocuments(ApplicationEntity applicationEntity, List<DocumentEntity> documents, ApplicationSignedDocumentEntity signedDocument,
|
||||
List<DocumentEntity> amendmentDocuments, List<DocumentEntity> evaluationDocuments, Long applicationId) {
|
||||
|
||||
private byte[] createZipWithDocuments(ApplicationEntity applicationEntity, List<DocumentEntity> documents,
|
||||
ApplicationSignedDocumentEntity signedDocument, Long applicationId) {
|
||||
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
|
||||
String s3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION, applicationEntity.getCall().getId(), applicationId,0L);
|
||||
|
||||
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
Long callId = applicationEntity.getCall().getId();
|
||||
// Add Application Documents
|
||||
String appS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.APPLICATION, callId, applicationId, 0L);
|
||||
for (DocumentEntity document : documents) {
|
||||
String fileName = Utils.extractFileName(document.getFilePath());
|
||||
addDocumentToZip(zos, s3Folder, document.getFilePath(), fileName);
|
||||
addDocumentToZip(zos, appS3Folder, document.getFilePath(), fileName);
|
||||
}
|
||||
|
||||
// Add Signed Document
|
||||
if (signedDocument != null) {
|
||||
String signedDocS3Folder = s3PathConfig.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, applicationEntity.getCall().getId(), applicationId,0L);
|
||||
String signedDocFileName = signedDocument.getFileName();
|
||||
addDocumentToZip(zos, signedDocS3Folder, signedDocument.getFilePath(), signedDocFileName);
|
||||
String signedFolder = "SIGNED_DOCUMENT/";
|
||||
String signedDocS3Folder = s3PathConfig.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId, 0L);
|
||||
String fileName = signedDocument.getFileName();
|
||||
addDocumentToZip(zos, signedDocS3Folder, signedDocument.getFilePath(), signedFolder + fileName);
|
||||
}
|
||||
// Add Amendment (Soccorso) Documents
|
||||
for (DocumentEntity amendmentDocument : amendmentDocuments) {
|
||||
String protocolNumber = fetchProtocolNumberForAmendment(amendmentDocument.getSourceId());
|
||||
String amendmentFolder = "SOCCORSO_" + protocolNumber + "/";
|
||||
String amendmentS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.AMENDMENT, callId, applicationId, amendmentDocument.getSourceId());
|
||||
String fileName = Utils.extractFileName(amendmentDocument.getFilePath());
|
||||
addDocumentToZip(zos, amendmentS3Folder, amendmentDocument.getFilePath(), amendmentFolder + fileName);
|
||||
}
|
||||
// Add Evaluation Documents
|
||||
for (DocumentEntity evaluationDocument : evaluationDocuments) {
|
||||
String evaluationFolder = "EVALUATION/";
|
||||
String evaluationS3Folder = s3PathConfig.generateDocumentPath(DocumentSourceTypeEnum.EVALUATION, callId, applicationId, evaluationDocument.getSourceId());
|
||||
String fileName = Utils.extractFileName(evaluationDocument.getFilePath());
|
||||
addDocumentToZip(zos, evaluationS3Folder, evaluationDocument.getFilePath(), evaluationFolder + fileName);
|
||||
}
|
||||
|
||||
zos.finish();
|
||||
return zipOutputStream.toByteArray();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error while creating ZIP file", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -24,7 +24,10 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -580,6 +583,10 @@ public class ApplicationEvaluationDao {
|
||||
CompanyEntity company = companyService.validateCompany(application.getCompanyId());
|
||||
response.setCompanyName(company.getCompanyName());
|
||||
}
|
||||
response.setAmountAccepted(application.getAmountAccepted());
|
||||
response.setAmountRequested(application.getAmountRequested());
|
||||
response.setDateAccepted(application.getDateAccepted());
|
||||
response.setDateRejected(application.getDateRejected());
|
||||
}
|
||||
|
||||
|
||||
@@ -594,6 +601,7 @@ public class ApplicationEvaluationDao {
|
||||
Optional<AssignedApplicationsEntity> assignedApplications =
|
||||
assignedApplicationsRepository.findByIdAndIsDeletedFalse(assignedApplicationId);
|
||||
ApplicationEvaluationEntity oldApplicationEvaluation = null;
|
||||
ApplicationEntity application = applicationService.validateApplication(assignedApplications.get().getApplication().getId());
|
||||
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
|
||||
if (existingEntityOptional.isPresent()) {
|
||||
entity = existingEntityOptional.get();
|
||||
@@ -610,9 +618,15 @@ public class ApplicationEvaluationDao {
|
||||
entity.setIsDeleted(false);
|
||||
setIfUpdated(entity::getNote, entity::setNote, req.getNote());
|
||||
setIfUpdated(entity::getMotivation, entity::setMotivation, req.getMotivation());
|
||||
if(Boolean.TRUE.equals(req.getApplicationStatus().equals(ApplicationStatusForEvaluation.APPROVED)) && (req.getAmountAccepted()==null || req.getAmountAccepted().compareTo(BigDecimal.ZERO) < 0)){
|
||||
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.AMOUNT_ACCEPTED_REQUIRED_WHILE_APPROVING_APPLICATION));
|
||||
}
|
||||
if (req.getAmountAccepted() != null && req.getAmountAccepted().compareTo(BigDecimal.ZERO) > 0) {
|
||||
application.setAmountAccepted(req.getAmountAccepted());
|
||||
}
|
||||
actionType = VersionActionTypeEnum.UPDATE;
|
||||
} else {
|
||||
ApplicationEntity application=entity.getAssignedApplicationsEntity().getApplication();
|
||||
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplicationsService.validateAssignedApplication(assignedApplicationId);
|
||||
entity = convertToEntity(user, req, assignedApplicationId);
|
||||
actionType = VersionActionTypeEnum.INSERT;
|
||||
|
||||
@@ -641,7 +655,6 @@ public class ApplicationEvaluationDao {
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplicationEvaluation).newData(entity).build());
|
||||
|
||||
if (status != null) {
|
||||
ApplicationEntity application = applicationService.validateApplication(assignedApplications.get().getApplication().getId());
|
||||
AssignedApplicationsEntity assignedApplicationsEntity = assignedApplications.get();
|
||||
return updateApplicationEvaluationStatus(application, assignedApplicationsEntity, status);
|
||||
} else {
|
||||
@@ -1799,6 +1812,11 @@ public class ApplicationEvaluationDao {
|
||||
existingEntity.setClosingDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
assignedApplicationsEntity.setStatus(AssignedApplicationEnum.CLOSE.getValue());
|
||||
}
|
||||
if (existingEntity.getStartDate() != null && existingEntity.getClosingDate() != null) {
|
||||
long activeDays = ChronoUnit.DAYS.between(existingEntity.getStartDate(), existingEntity.getClosingDate());
|
||||
activeDays -= existingEntity.getSuspendedDays() != null ? existingEntity.getSuspendedDays() : 0;
|
||||
existingEntity.setActiveDays(activeDays);
|
||||
}
|
||||
entity = applicationEvaluationRepository.save(existingEntity);
|
||||
assignedApplicationsRepository.save(assignedApplicationsEntity);
|
||||
|
||||
@@ -1813,9 +1831,15 @@ public class ApplicationEvaluationDao {
|
||||
|
||||
|
||||
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.APPROVED.getValue())))) {
|
||||
application.setDateAccepted(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
application = applicationRepository.save(application);
|
||||
emailNotificationDao.sendAdmissibilityNotificationEmailForApprovedApplication(application);
|
||||
}
|
||||
if (Boolean.TRUE.equals(statusType.equals((ApplicationStatusTypeEnum.REJECTED.getValue())))) {
|
||||
application.setDateRejected(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
application.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
application = applicationRepository.save(application);
|
||||
emailNotificationDao.sendInadmissibilityEmailForRejectedApplication(application,existingEntity);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.entities.*;
|
||||
@@ -66,7 +67,7 @@ public class CompanyDao {
|
||||
if (existingCompany != null) {
|
||||
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), existingCompany.getId()).orElse(null);
|
||||
if (existingRelation == null) {
|
||||
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant());
|
||||
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant(),companyRequest);
|
||||
|
||||
/** This code is responsible for adding a version history log for "adding user with company" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
@@ -83,7 +84,7 @@ public class CompanyDao {
|
||||
/** This code is responsible for adding a version history log for "creating company" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(companyData).build());
|
||||
|
||||
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant());
|
||||
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant(),companyRequest);
|
||||
|
||||
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
|
||||
}
|
||||
@@ -107,7 +108,7 @@ public class CompanyDao {
|
||||
}
|
||||
}
|
||||
|
||||
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity, Boolean isLegalRepresentant) {
|
||||
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity, Boolean isLegalRepresentant,CompanyRequest companyRequest) {
|
||||
|
||||
UserWithCompanyEntity userWithCompanyEntity = new UserWithCompanyEntity();
|
||||
if (userEntity.getBeneficiary() != null) {
|
||||
@@ -117,6 +118,11 @@ public class CompanyDao {
|
||||
userWithCompanyEntity.setCompanyId(companyEntity.getId());
|
||||
userWithCompanyEntity.setUserId(userEntity.getId());
|
||||
userWithCompanyEntity.setIsLegalRepresentant(isLegalRepresentant);
|
||||
userWithCompanyEntity.setEmail(companyRequest.getEmail());
|
||||
userWithCompanyEntity.setPec(companyRequest.getPec());
|
||||
userWithCompanyEntity.setContactName(companyRequest.getContactName());
|
||||
userWithCompanyEntity.setContactEmail(companyRequest.getContactEmail());
|
||||
userWithCompanyEntity.setJson(Utils.convertMapIntoJsonString(companyRequest.getVatCheckResponse()) );
|
||||
UserWithCompanyEntity userWithCompany = userWithCompanyRepository.save(userWithCompanyEntity);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "adding user with company" operation. **/
|
||||
@@ -135,12 +141,8 @@ public class CompanyDao {
|
||||
entity.setProvince(request.getProvince());
|
||||
entity.setCap(request.getCap());
|
||||
entity.setCountry(request.getCountry());
|
||||
entity.setPec(request.getPec());
|
||||
entity.setEmail(request.getEmail());
|
||||
entity.setNumberOfEmployees(request.getNumberOfEmployees());
|
||||
entity.setAnnualRevenue(request.getAnnualRevenue());
|
||||
entity.setContactName(request.getContactName());
|
||||
entity.setContactEmail(request.getContactEmail());
|
||||
entity.setHub(userEntity.getHub());
|
||||
return entity;
|
||||
}
|
||||
@@ -157,8 +159,8 @@ public class CompanyDao {
|
||||
response.setProvince(entity.getProvince());
|
||||
response.setCap(entity.getCap());
|
||||
response.setCountry(entity.getCountry());
|
||||
response.setPec(entity.getPec());
|
||||
response.setEmail(entity.getEmail());
|
||||
response.setPec(userWithCompanyEntity.getPec());
|
||||
response.setEmail(userWithCompanyEntity.getEmail());
|
||||
response.setNumberOfEmployees(entity.getNumberOfEmployees());
|
||||
response.setAnnualRevenue(entity.getAnnualRevenue());
|
||||
if(userWithCompanyEntity!=null) {
|
||||
@@ -166,8 +168,8 @@ public class CompanyDao {
|
||||
}
|
||||
response.setCreatedDate(entity.getCreatedDate());
|
||||
response.setUpdatedDate(entity.getUpdatedDate());
|
||||
response.setContactName(entity.getContactName());
|
||||
response.setContactEmail(entity.getContactEmail());
|
||||
response.setContactName(userWithCompanyEntity.getContactName());
|
||||
response.setContactEmail(userWithCompanyEntity.getContactEmail());
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -178,7 +180,6 @@ public class CompanyDao {
|
||||
CompanyEntity oldCompanyData = Utils.getClonedEntityForData(companyEntity);
|
||||
|
||||
setIfUpdated(companyEntity::getCompanyName, companyEntity::setCompanyName, companyRequest.getCompanyName());
|
||||
setIfUpdated(companyEntity::getVatNumber, companyEntity::setVatNumber, companyRequest.getVatNumber());
|
||||
setIfUpdated(companyEntity::getCodiceFiscale, companyEntity::setCodiceFiscale, companyRequest.getCodiceFiscale());
|
||||
setIfUpdated(companyEntity::getAddress, companyEntity::setAddress, companyRequest.getAddress());
|
||||
setIfUpdated(companyEntity::getPhoneNumber, companyEntity::setPhoneNumber, companyRequest.getPhoneNumber());
|
||||
@@ -186,12 +187,17 @@ public class CompanyDao {
|
||||
setIfUpdated(companyEntity::getProvince, companyEntity::setProvince, companyRequest.getProvince());
|
||||
setIfUpdated(companyEntity::getCap, companyEntity::setCap, companyRequest.getCap());
|
||||
setIfUpdated(companyEntity::getCountry, companyEntity::setCountry, companyRequest.getCountry());
|
||||
setIfUpdated(companyEntity::getPec, companyEntity::setPec, companyRequest.getPec());
|
||||
setIfUpdated(companyEntity::getEmail, companyEntity::setEmail, companyRequest.getEmail());
|
||||
setIfUpdated(companyEntity::getNumberOfEmployees, companyEntity::setNumberOfEmployees, companyRequest.getNumberOfEmployees());
|
||||
setIfUpdated(companyEntity::getAnnualRevenue, companyEntity::setAnnualRevenue, companyRequest.getAnnualRevenue());
|
||||
setIfUpdated(companyEntity::getContactName, companyEntity::setContactName, companyRequest.getContactName());
|
||||
setIfUpdated(companyEntity::getContactEmail, companyEntity::setContactEmail, companyRequest.getContactEmail());
|
||||
//
|
||||
// if(StringUtils.isNotBlank(companyRequest.getVatNumber())) {
|
||||
// CompanyEntity existingCompany = companyRepository.findByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId());
|
||||
// if(existingCompany!=null){
|
||||
// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
|
||||
// }
|
||||
// companyEntity.setVatNumber(companyRequest.getVatNumber());
|
||||
//
|
||||
// }
|
||||
companyRepository.save(companyEntity);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update company" operation. **/
|
||||
@@ -201,8 +207,15 @@ public class CompanyDao {
|
||||
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
|
||||
//cloned entity for old data
|
||||
UserWithCompanyEntity oldUserWithCompanyData = Utils.getClonedEntityForData(userWithCompanyEntity);
|
||||
|
||||
Utils.setIfUpdated(userWithCompanyEntity::getIsLegalRepresentant, userWithCompanyEntity::setIsLegalRepresentant, companyRequest.getIsLegalRepresentant());
|
||||
if(StringUtils.isNotBlank(companyRequest.getVatNumber())) {
|
||||
String responseJson = companyRequest.getVatCheckResponse() != null ? Utils.convertMapIntoJsonString(companyRequest.getVatCheckResponse()) : null;
|
||||
setIfUpdated(userWithCompanyEntity::getJson, userWithCompanyEntity::setJson, responseJson);
|
||||
}
|
||||
setIfUpdated(userWithCompanyEntity::getPec, userWithCompanyEntity::setPec, userWithCompanyEntity.getPec());
|
||||
setIfUpdated(userWithCompanyEntity::getEmail, userWithCompanyEntity::setEmail, userWithCompanyEntity.getEmail());
|
||||
setIfUpdated(userWithCompanyEntity::getContactName, userWithCompanyEntity::setContactName, companyRequest.getContactName());
|
||||
setIfUpdated(userWithCompanyEntity::getContactEmail, userWithCompanyEntity::setContactEmail, companyRequest.getContactEmail());
|
||||
setIfUpdated(userWithCompanyEntity::getIsLegalRepresentant, userWithCompanyEntity::setIsLegalRepresentant, companyRequest.getIsLegalRepresentant());
|
||||
userWithCompanyEntity = userWithCompanyRepository.save(userWithCompanyEntity);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update company" operation. **/
|
||||
@@ -254,7 +267,7 @@ public class CompanyDao {
|
||||
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
|
||||
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
|
||||
}
|
||||
|
||||
|
||||
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
|
||||
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, compnayId).orElseThrow(
|
||||
() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_COMPANY_RELATION_NOT_FOUND)));
|
||||
@@ -277,39 +290,59 @@ public class CompanyDao {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT));
|
||||
}
|
||||
|
||||
for(ApplicationEntity application:userApplications){
|
||||
ApplicationEntity oldApplication = Utils.getClonedEntityForData(application);
|
||||
application.setIsDeleted(Boolean.TRUE);
|
||||
userApplications = userApplications.stream()
|
||||
.peek(application -> {
|
||||
ApplicationEntity oldApplication = Utils.getClonedEntityForData(application);
|
||||
application.setIsDeleted(Boolean.TRUE);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Soft delete application" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldApplication).newData(application).build());
|
||||
|
||||
}
|
||||
/** This code is responsible for adding a version history log for the "Soft delete Faq" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder()
|
||||
.request(request)
|
||||
.actionType(VersionActionTypeEnum.SOFT_DELETE)
|
||||
.oldData(oldApplication)
|
||||
.newData(application)
|
||||
.build()
|
||||
);
|
||||
})
|
||||
.toList();
|
||||
applicationRepository.saveAll(userApplications);
|
||||
|
||||
for(FaqEntity faq:faqs){
|
||||
FaqEntity oldFaq = Utils.getClonedEntityForData(faq);
|
||||
faq.setIsDeleted(Boolean.TRUE);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Soft delete Faq" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldFaq).newData(faq).build());
|
||||
}
|
||||
faqs = faqs.stream()
|
||||
.peek(faq -> {
|
||||
FaqEntity oldFaq = Utils.getClonedEntityForData(faq);
|
||||
faq.setIsDeleted(Boolean.TRUE);
|
||||
/** This code is responsible for adding a version history log for the "Soft delete Faq" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder()
|
||||
.request(request)
|
||||
.actionType(VersionActionTypeEnum.SOFT_DELETE)
|
||||
.oldData(oldFaq)
|
||||
.newData(faq)
|
||||
.build()
|
||||
);
|
||||
})
|
||||
.toList();
|
||||
faqRepository.saveAll(faqs);
|
||||
|
||||
for(BeneficiaryPreferredCallEntity beneficiaryPreferredCall:preferredCallEntities){
|
||||
BeneficiaryPreferredCallEntity oldPreferredCall = Utils.getClonedEntityForData(beneficiaryPreferredCall);
|
||||
beneficiaryPreferredCall.setIsDeleted(Boolean.TRUE);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Soft Delete BeneficiaryPreferredCall" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldPreferredCall).newData(beneficiaryPreferredCall).build());
|
||||
|
||||
}
|
||||
preferredCallEntities = preferredCallEntities.stream()
|
||||
.peek(beneficiaryPreferredCall -> {
|
||||
BeneficiaryPreferredCallEntity oldPreferredCall = Utils.getClonedEntityForData(beneficiaryPreferredCall);
|
||||
beneficiaryPreferredCall.setIsDeleted(Boolean.TRUE);
|
||||
/** This code is responsible for adding a version history log for the "Soft Delete BeneficiaryPreferredCall" operation. **/
|
||||
loggingUtil.addVersionHistory(
|
||||
VersionHistoryRequest.builder()
|
||||
.request(request)
|
||||
.actionType(VersionActionTypeEnum.SOFT_DELETE)
|
||||
.oldData(oldPreferredCall)
|
||||
.newData(beneficiaryPreferredCall)
|
||||
.build()
|
||||
);
|
||||
})
|
||||
.toList();
|
||||
beneficiaryPreferredCallRepository.saveAll(preferredCallEntities);
|
||||
|
||||
if(userCompanyDelegationEntity!=null){
|
||||
if(userCompanyDelegationEntity!=null){
|
||||
UserCompanyDelegationEntity oldUserWithCompanyDelegation = Utils.getClonedEntityForData(userCompanyDelegationEntity);
|
||||
userCompanyDelegationEntity.setStatus( UserCompanyDelegationStatusEnum.INACTIVE.getValue());
|
||||
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
|
||||
|
||||
@@ -1,23 +1,36 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserActionEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
|
||||
import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.enums.CallStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserStatusEnum;
|
||||
import net.gepafin.tendermanagement.model.response.ApplicationWidgetResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.BeneficiaryWidgetResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.Widget1;
|
||||
import net.gepafin.tendermanagement.model.response.SuperAdminWidgetResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.CallRepository;
|
||||
import net.gepafin.tendermanagement.repositories.CompanyRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class DashboardDao {
|
||||
@@ -33,15 +46,24 @@ public class DashboardDao {
|
||||
|
||||
@Autowired
|
||||
private CompanyRepository companyRepository;
|
||||
|
||||
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
@Autowired
|
||||
private BeneficiaryPreferredCallRepository beneficiaryPreferredCallRepository;
|
||||
|
||||
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
@Autowired
|
||||
private UserActionsRepository userActionsRepository;
|
||||
|
||||
public SuperAdminWidgetResponseBean getDashboardWidget(UserEntity requestedUserEntity) {
|
||||
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
|
||||
widgetResponseBean.setWidget1(createWidget1(requestedUserEntity));
|
||||
// List<Object[]> widgetBars = callRepository.findApplicationsPerCall();
|
||||
// widgetResponseBean.setWidgetBars(widgetBars);
|
||||
Map<String, Object> widgetBars =getStatistics(requestedUserEntity);
|
||||
widgetResponseBean.setWidgetBars(widgetBars);
|
||||
return widgetResponseBean;
|
||||
}
|
||||
|
||||
@@ -54,7 +76,8 @@ public class DashboardDao {
|
||||
setSubmittedApplications(widget1, requestedUserEntity);
|
||||
setDraftApplications(widget1, requestedUserEntity);
|
||||
setNumberOfCompanies(widget1, requestedUserEntity);
|
||||
|
||||
setAmountRequested(widget1,requestedUserEntity);
|
||||
setAmountAccepted(widget1,requestedUserEntity);
|
||||
return widget1;
|
||||
}
|
||||
|
||||
@@ -71,6 +94,20 @@ public class DashboardDao {
|
||||
}
|
||||
}
|
||||
|
||||
private void setAmountRequested(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
BigDecimal amountRequested = applicationRepository.findTotalAmountRequestedOfApplication(requestedUserEntity.getHub().getId());
|
||||
if (amountRequested != null) {
|
||||
widget1.setTotalAmountRequested(amountRequested);
|
||||
}
|
||||
}
|
||||
|
||||
private void setAmountAccepted(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
BigDecimal amountAccepted = applicationRepository.findTotalAmountAcceptedOfApplication(requestedUserEntity.getHub().getId());
|
||||
if (amountAccepted != null) {
|
||||
widget1.setTotalAmountAccepted(amountAccepted);
|
||||
}
|
||||
}
|
||||
|
||||
private void setRegisteredUsers(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
Long activeUsers = userRepository.countByStatusAndRoleEntityRoleTypeAndHubId(UserStatusEnum.ACTIVE.getValue(),
|
||||
RoleStatusEnum.ROLE_BENEFICIARY.getValue(), requestedUserEntity.getHub().getId());
|
||||
@@ -106,14 +143,26 @@ public class DashboardDao {
|
||||
}
|
||||
|
||||
public BeneficiaryWidgetResponseBean getDashboardWidgetForBeneficiary(UserEntity userEntity,
|
||||
CompanyEntity company) {
|
||||
CompanyEntity company) {
|
||||
BeneficiaryWidgetResponseBean beneficiaryWidgetResponseBean = BeneficiaryWidgetResponseBean.builder()
|
||||
.numberOfApplications(0L).numberOfCalls(0L).numberOfIntegratedDocuments(0L).build();
|
||||
Long activeCalls = callRepository.countByStatusAndHubId(CallStatusEnum.PUBLISH.getValue(), userEntity.getHub().getId());
|
||||
if (activeCalls != null) {
|
||||
beneficiaryWidgetResponseBean.setNumberOfCalls(activeCalls);
|
||||
UserWithCompanyEntity userWithCompanyEntity = companyService.getUserWithCompany(userEntity.getId(), company.getId());
|
||||
|
||||
List<BeneficiaryPreferredCallEntity> preferredCalls = beneficiaryPreferredCallRepository
|
||||
.findByUserIdAndUserWithCompanyIdAndIsDeletedFalse(userEntity.getId(), userWithCompanyEntity.getId());
|
||||
|
||||
if (preferredCalls != null && !preferredCalls.isEmpty()) {
|
||||
List<Long> callIds = preferredCalls.stream()
|
||||
.map(BeneficiaryPreferredCallEntity::getCallId)
|
||||
.collect(Collectors.toList());
|
||||
List<CallEntity> callEntities = callRepository.findByIdIn(callIds);
|
||||
long activeCallsCount = callEntities.stream()
|
||||
.filter(call -> CallStatusEnum.PUBLISH.getValue().equals(call.getStatus())
|
||||
&& userEntity.getHub().getId().equals(call.getHub().getId()))
|
||||
.count();
|
||||
|
||||
beneficiaryWidgetResponseBean.setNumberOfCalls(activeCallsCount);
|
||||
}
|
||||
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),company.getId());
|
||||
Long activeApplication = applicationRepository.countSubmittedApplicationsByUserId(userEntity.getId(),
|
||||
userWithCompanyEntity.getId());
|
||||
if (activeApplication != null) {
|
||||
@@ -121,4 +170,99 @@ public class DashboardDao {
|
||||
}
|
||||
return beneficiaryWidgetResponseBean;
|
||||
}
|
||||
|
||||
public Map<String, Object> getStatistics(UserEntity requestedUser) {
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
|
||||
// Get applications per call
|
||||
List<Object[]> applicationsPerCall = applicationRepository.findApplicationsPerCallWithName(requestedUser.getHub().getId());
|
||||
stats.put(GepafinConstant.APPLICATION_PER_CALL, applicationsPerCall.stream().map(result -> {
|
||||
Map<String, Object> callData = new HashMap<>();
|
||||
callData.put(GepafinConstant.CALL_NAME, result[0]); // Call name
|
||||
callData.put(GepafinConstant.NUMBER_OF_APPLICATIONS, result[1]); // Application count
|
||||
return callData;
|
||||
}).toList());
|
||||
|
||||
// Get applications grouped by status
|
||||
List<Object[]> applicationsByStatus = applicationRepository.findApplicationsByStatus(requestedUser.getHub().getId());
|
||||
stats.put(GepafinConstant.APPLICATION_PER_STATUS, applicationsByStatus.stream().map(result -> {
|
||||
Map<String, Object> statusData = new HashMap<>();
|
||||
statusData.put(GepafinConstant.STATUS, result[0]); // Application status
|
||||
statusData.put(GepafinConstant.NUMBER_OF_APPLICATIONS, result[1]); // Count of applications
|
||||
return statusData;
|
||||
}).toList());
|
||||
|
||||
return stats;
|
||||
}
|
||||
// public Page<UserActionEntity> getUserAction(UserEntity requestedUserEntity){
|
||||
// Pageable pageable = PageRequest.of(0, 20); // Get the first 20 records
|
||||
// List<String> roles=List.of(RoleStatusEnum.ROLE_PRE_INSTRUCTOR.getValue(),RoleStatusEnum.ROLE_GEPAFIN_OPERATOR.getValue(),RoleStatusEnum.ROLE_INSTRUCTOR_MANAGER.getValue());
|
||||
// Page<UserActionEntity> userActionEntities=userActionsRepository.findActionsByRoleNamesAndHubId(roles,requestedUserEntity.getHub().getId(),pageable);
|
||||
// return userActionEntities;
|
||||
// }
|
||||
public ApplicationWidgetResponseBean getApplicationDetails(UserEntity userEntity) {
|
||||
ApplicationWidgetResponseBean applicationWidgetResponseBean = initializeResponseBean();
|
||||
|
||||
Long hubId = userEntity.getHub().getId();
|
||||
|
||||
setApplicationCounts(applicationWidgetResponseBean, hubId);
|
||||
calculateEvaluationAverageTime(applicationWidgetResponseBean, hubId);
|
||||
|
||||
return applicationWidgetResponseBean;
|
||||
}
|
||||
|
||||
private ApplicationWidgetResponseBean initializeResponseBean() {
|
||||
return ApplicationWidgetResponseBean.builder()
|
||||
.numberOfApplication(0L)
|
||||
.numberOfAssignedApplication(0L)
|
||||
.numberOfAcceptedApplication(0L)
|
||||
.numberOfApplicationInAmendmentState(0L)
|
||||
.numberOfDueApplication(0L)
|
||||
.evaluationAverageTime(BigDecimal.ZERO)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void setApplicationCounts(ApplicationWidgetResponseBean responseBean, Long hubId) {
|
||||
Long activeApplications = applicationRepository.countApplicationsByHubId(hubId);
|
||||
if (activeApplications != null) {
|
||||
responseBean.setNumberOfApplication(activeApplications);
|
||||
}
|
||||
|
||||
Long assignedApplications = applicationRepository.countAssignedApplicationsByHubId(hubId);
|
||||
if (assignedApplications != null) {
|
||||
responseBean.setNumberOfAssignedApplication(assignedApplications);
|
||||
}
|
||||
|
||||
Long approvedApplications = applicationRepository.countApprovedApplicationsByHubId(hubId);
|
||||
if (approvedApplications != null) {
|
||||
responseBean.setNumberOfAcceptedApplication(approvedApplications);
|
||||
}
|
||||
|
||||
Long soccorsoApplications = applicationRepository.countSoccorsoApplicationsByHubId(hubId);
|
||||
if (soccorsoApplications != null) {
|
||||
responseBean.setNumberOfApplicationInAmendmentState(soccorsoApplications);
|
||||
}
|
||||
}
|
||||
|
||||
private void calculateEvaluationAverageTime(ApplicationWidgetResponseBean responseBean, Long hubId) {
|
||||
List<Long> applicationIds = applicationRepository.findApplicationIdsByHubId(hubId);
|
||||
|
||||
if (Boolean.FALSE.equals(applicationIds.isEmpty())) {
|
||||
BigDecimal averageTime = applicationEvaluationRepository.findAverageEvaluationTimeByApplicationIds(applicationIds);
|
||||
responseBean.setEvaluationAverageTime(averageTime != null ? averageTime : BigDecimal.ZERO);
|
||||
}
|
||||
LocalDate twoDaysLater = LocalDate.now().plusDays(2);
|
||||
|
||||
Long dueApplications = applicationEvaluationRepository.countDueApplicationsBetween(
|
||||
applicationIds,
|
||||
LocalDate.now(),
|
||||
twoDaysLater
|
||||
);
|
||||
|
||||
if (dueApplications != null) {
|
||||
responseBean.setNumberOfDueApplication(dueApplications);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -103,8 +103,10 @@ public class EmailNotificationDao {
|
||||
|
||||
Optional<ApplicationEvaluationEntity> applicationEvaluationEntity = applicationEvaluationRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId());
|
||||
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
|
||||
String companyEmail = company.getEmail();
|
||||
String contactEmail = company.getContactEmail();
|
||||
|
||||
UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId());
|
||||
String companyEmail = userWithCompany.getEmail();
|
||||
String contactEmail = userWithCompany.getContactEmail();
|
||||
|
||||
if (companyEmail != null && !companyEmail.isEmpty()) {
|
||||
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(), RecipientTypeEnum.COMPANY,company.getId() ,
|
||||
|
||||
@@ -309,6 +309,10 @@ public class FlowFormDao {
|
||||
if(applicationEntity.getProtocol() != null) {
|
||||
nextOrPreviousFormResponse.setProtocolNumber(applicationEntity.getProtocol().getProtocolNumber());
|
||||
}
|
||||
nextOrPreviousFormResponse.setAmountAccepted(applicationEntity.getAmountAccepted());
|
||||
nextOrPreviousFormResponse.setAmountRequested(applicationEntity.getAmountRequested());
|
||||
nextOrPreviousFormResponse.setDateAccepted(applicationEntity.getDateAccepted());
|
||||
nextOrPreviousFormResponse.setDateRejected(applicationEntity.getDateRejected());
|
||||
return nextOrPreviousFormResponse;
|
||||
}
|
||||
|
||||
|
||||
@@ -177,7 +177,7 @@ public class NotificationDao {
|
||||
ApplicationEntity application = applicationService.validateApplication(applicationEvaluationEntity.getApplicationId());
|
||||
if (instructorId != null) {
|
||||
NotificationReq notificationreq = createNotificationReq(notificationTypeEnum.getValue(), placeHolders, instructorId, application.getUserWithCompany(),
|
||||
listOf(application.getCompanyId()));
|
||||
null);
|
||||
sendNotification(notificationreq);
|
||||
}
|
||||
}
|
||||
@@ -187,7 +187,7 @@ public class NotificationDao {
|
||||
UserEntity userEntity1 = user.get(0);
|
||||
if (userEntity1 != null) {
|
||||
NotificationReq notificationreq = createNotificationReq(notificationTypeEnum.getValue(), placeHolders, userEntity1.getId(), application.getUserWithCompany(),
|
||||
listOf(application.getCompanyId()));
|
||||
null);
|
||||
sendNotification(notificationreq);
|
||||
}
|
||||
}
|
||||
@@ -253,19 +253,26 @@ public class NotificationDao {
|
||||
notificationRepository.save(notificationEntity);
|
||||
}
|
||||
|
||||
public List<NotificationResponse> getNotificationByCompanyIdAndUserId(Long userId, Long companyId) {
|
||||
public List<NotificationResponse> getNotificationByCompanyIdAndUserId(Long userId, Long companyId, List<NotificationEnum> statuses) {
|
||||
|
||||
companyDao.validateCompany(companyId);
|
||||
userDao.validateUser(userId);
|
||||
|
||||
UserWithCompanyEntity userWithCompanyData = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalseForNotification(userId, companyId);
|
||||
if (userWithCompanyData == null) {
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, GepafinConstant.USER_MUST_BE_ASSOCIATED_WITH_COMPANY);
|
||||
List<NotificationEntity> notificationEntities = notificationRepository.findByUserIdAndIsDeletedFalse(userId);
|
||||
UserWithCompanyEntity userWithCompany = null;
|
||||
List<String> statusStrings;
|
||||
if (companyId != null) {
|
||||
userWithCompany = companyDao.validateUserWithCompny(userId, companyId);
|
||||
}
|
||||
|
||||
List<NotificationEntity> notifications = notificationRepository.findByUserWithCompanyIdAndUserIdAndIsDeletedFalse(userWithCompanyData.getId(),
|
||||
userWithCompanyData.getUserId());
|
||||
return notifications.stream().map(this::convertNotificationEntityToNotificationResponse).toList();
|
||||
if (statuses != null) {
|
||||
statusStrings = statuses.stream().map(NotificationEnum::name)
|
||||
.toList();
|
||||
notificationEntities = notificationRepository.findByUserIdAndIsDeletedFalseAndStatusIn(userId, statusStrings);
|
||||
|
||||
if (userWithCompany != null) {
|
||||
notificationEntities = notificationRepository.findByUserIdAndUserWithCompanyIdAndIsDeletedFalseAndStatusIn(userId, userWithCompany.getId(), statusStrings);
|
||||
}
|
||||
}
|
||||
|
||||
return notificationEntities.stream().map(this::convertNotificationEntityToNotificationResponse).toList();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -109,76 +109,7 @@ public class PdfDao {
|
||||
document.add(new Paragraph(" ")); // Add line break
|
||||
}
|
||||
document.add(new Paragraph("\n")); // Add line break
|
||||
Font boldSmallFont = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD,new BaseColor(105, 105, 105));
|
||||
|
||||
// Adding the "Documenti Allegati" section title
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//// pageEvent.setTotalPages(writer.getPageNumber());
|
||||
// document.newPage();
|
||||
//// pageEvent.setTotalPages(writer.getPageNumber());
|
||||
// document.add(new Paragraph("Documenti Allegati", sectionFont));
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//// 1. Autocertificazione possesso Requisiti
|
||||
// Paragraph p1 = new Paragraph();
|
||||
// p1.add(new Chunk("1. ", boldSmallFont));
|
||||
// p1.add(new Chunk("Autocertificazione possesso Requisiti ", boldSmallFont));
|
||||
// p1.add(new Chunk("ai sensi degli artt. 46 e 47 del DPR 445/2000", smallFont));
|
||||
// document.add(p1);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//
|
||||
//// 2. Informativa Privacy relativa al trattamento dei dati personali
|
||||
// Paragraph p2 = new Paragraph();
|
||||
// p2.add(new Chunk("2. ", boldSmallFont));
|
||||
// p2.add(new Chunk("Informativa Privacy relativa al trattamento dei dati personali", boldSmallFont));
|
||||
// document.add(p2);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//// 3. Dati richiesti per la valutazione dell’adeguatezza dei flussi finanziari
|
||||
// Paragraph p3 = new Paragraph();
|
||||
// p3.add(new Chunk("3. ", boldSmallFont));
|
||||
// p3.add(new Chunk("Dati richiesti per la valutazione dell’adeguatezza dei flussi finanziari prospettici come da tabella di cui all’Appendice 9", boldSmallFont));
|
||||
// document.add(p3);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//// 4. Rilevazione Centrale dei Rischi
|
||||
// Paragraph p4 = new Paragraph();
|
||||
// p4.add(new Chunk("4. ", boldSmallFont));
|
||||
// p4.add(new Chunk("Rilevazione Centrale dei Rischi riferita agli ultimi 36 mesi disponibili alla data di presentazione della Domanda", boldSmallFont));
|
||||
// document.add(p4);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//// 5. Schema di presentazione dei dati di bilancio
|
||||
// Paragraph p5 = new Paragraph();
|
||||
// p5.add(new Chunk("5. ", boldSmallFont));
|
||||
// p5.add(new Chunk("Schema di presentazione dei dati di bilancio", boldSmallFont));
|
||||
// document.add(p5);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//// 6. Dettagli bilanci in forma abbreviata
|
||||
// Paragraph p6 = new Paragraph();
|
||||
// p6.add(new Chunk("6. ", boldSmallFont));
|
||||
// p6.add(new Chunk("Dettagli bilanci in forma abbreviata", boldSmallFont));
|
||||
// document.add(p6);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
//
|
||||
//// 7. Relazione aziendale illustrativa
|
||||
// Paragraph p7 = new Paragraph();
|
||||
// p7.add(new Chunk("7. ", boldSmallFont));
|
||||
// p7.add(new Chunk("Relazione aziendale illustrativa", boldSmallFont));
|
||||
// document.add(p7);
|
||||
// document.add(new Paragraph(" "));
|
||||
//
|
||||
// addColoredLines(writer,document,greenColor);
|
||||
|
||||
document.close();
|
||||
|
||||
@@ -488,12 +419,19 @@ public class PdfDao {
|
||||
.orElse(null); // If no match is found, set label to null
|
||||
// Find the form field in the response that matches the contentId
|
||||
if (name.equals("paragraph")){
|
||||
String paragraph = content.getSettings().stream()
|
||||
.filter(setting -> "text".equals(setting.getName())) // Filter settings by name
|
||||
.map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
||||
.map(Object::toString) // Convert the value to a string
|
||||
.findFirst() // Get the first matching value
|
||||
.orElse(null);
|
||||
// String paragraph = content.getSettings().stream()
|
||||
// .filter(setting -> "text".equals(setting.getName())) // Filter settings by name
|
||||
// .map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
||||
// .map(Object::toString) // Convert the value to a string
|
||||
// .findFirst() // Get the first matching value
|
||||
// .orElse(null);
|
||||
String paragraph = content.getSettings().stream()
|
||||
.filter(setting -> "text".equals(setting.getName())) // Filter settings by name
|
||||
.map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
||||
.map(value -> value != null ? value.toString() : " ") // Replace null with an empty string
|
||||
.findFirst() // Get the first matching value
|
||||
.orElse(null); // Return null if no value is found
|
||||
|
||||
Paragraph labelParagraph = new Paragraph();
|
||||
PdfPCell labelCell = new PdfPCell(PdfUtils.htmlToPdfPCell(paragraph,labelFont));
|
||||
labelCell.setBorder(Rectangle.NO_BORDER);
|
||||
|
||||
@@ -6,21 +6,15 @@ import net.gepafin.tendermanagement.config.SamlSuccessHandler;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionContextEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionLogsEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.*;
|
||||
import net.gepafin.tendermanagement.model.request.*;
|
||||
import net.gepafin.tendermanagement.model.response.CompanyResponse;
|
||||
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
|
||||
import net.gepafin.tendermanagement.model.response.UserResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.*;
|
||||
import net.gepafin.tendermanagement.model.util.JWTToken;
|
||||
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.service.HubService;
|
||||
import net.gepafin.tendermanagement.service.RoleService;
|
||||
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
|
||||
import net.gepafin.tendermanagement.service.impl.AuthenticationService;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
@@ -39,6 +33,7 @@ import org.springframework.stereotype.Component;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
|
||||
@@ -90,6 +85,18 @@ public class UserDao {
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private SystemEmailTemplatesService systemEmailTemplatesService;
|
||||
|
||||
@Autowired
|
||||
private EmailLogDao emailLogDao;
|
||||
|
||||
@Autowired
|
||||
private EmailNotificationDao emailNotificationDao;
|
||||
|
||||
@Value("${fe.base.url}")
|
||||
private String feBaseUrl;
|
||||
|
||||
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
|
||||
|
||||
if (StringUtils.isEmpty(userReq.getHubUuid())) {
|
||||
@@ -120,9 +127,35 @@ public class UserDao {
|
||||
/** This code is responsible for adding a version history log for the "Create user" operation. **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).newData(userEntity).build());
|
||||
|
||||
if(beneficiary == null){
|
||||
sendEmailToOnboardingUser(userEntity);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
public void sendEmailToOnboardingUser(UserEntity userEntity){
|
||||
SystemEmailTemplateResponse emailTemplate = systemEmailTemplatesService.retrieveTemplateByTypeAndCall(
|
||||
SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.USER_ONBOARDING, userEntity.getHub(), null);
|
||||
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(emailTemplate.getEmailScenario(), RecipientTypeEnum.USER, userEntity.getId(), userEntity.getEmail(),
|
||||
userEntity.getId(), null, null, null);
|
||||
String firstName = userEntity.getFirstName() != null ? userEntity.getFirstName() : "";
|
||||
String lastName = userEntity.getLastName() != null ? userEntity.getLastName() : "";
|
||||
String userName = String.join(" ", firstName, lastName).trim();
|
||||
String subject = Utils.replacePlaceholders(emailTemplate.getSubject(), Map.of(
|
||||
"{{user_name}}", userName
|
||||
));
|
||||
String body = Utils.replacePlaceholders(emailTemplate.getHtmlContent(), Map.of(
|
||||
"{{user_name}}", userName,
|
||||
"{{user_email}}", userEntity.getEmail()
|
||||
));
|
||||
|
||||
emailNotificationDao.sendMail(
|
||||
userEntity.getHub().getId(),
|
||||
subject,
|
||||
body,
|
||||
List.of(userEntity.getEmail()),
|
||||
emailLogRequest
|
||||
);
|
||||
}
|
||||
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq, HubEntity hub) {
|
||||
BeneficiaryEntity beneficiaryEntity = null;
|
||||
if (RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType())) {
|
||||
@@ -157,6 +190,8 @@ public class UserDao {
|
||||
userReq.setHubUuid(userEntity.getHub().getUniqueUuid());
|
||||
}else {
|
||||
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale(), userReq.getHubUuid());
|
||||
RoleEntity roleEntity = roleDao.getRoleByType(RoleStatusEnum.ROLE_BENEFICIARY);
|
||||
userReq.setRoleId(roleEntity.getId());
|
||||
}
|
||||
|
||||
if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
|
||||
@@ -164,12 +199,10 @@ public class UserDao {
|
||||
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
|
||||
}
|
||||
log.info("Creating user with email: {}", userReq.getEmail());
|
||||
if (userRepository.existsByEmailIgnoreCaseAndHubUniqueUuid(userReq.getEmail(), userReq.getHubUuid())) {
|
||||
log.error("User creation failed: Email {} already exists", userReq.getEmail());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
|
||||
}
|
||||
if (Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getCodiceFiscale()))
|
||||
RoleEntity roleEntity = roleService.validateRole(userReq.getRoleId());
|
||||
validateDuplicateEmail(userReq.getEmail(), userReq.getHubUuid(), roleEntity.getRoleType());
|
||||
|
||||
if (Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getCodiceFiscale()))
|
||||
&& userRepository.existsByBeneficiaryCodiceFiscaleAndHubId(userReq.getCodiceFiscale(), hub.getId())) {
|
||||
log.error("User creation failed: CodiceFiscale {} already exists", userReq.getCodiceFiscale());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
@@ -192,7 +225,30 @@ public class UserDao {
|
||||
}
|
||||
}
|
||||
|
||||
private void validatePassword(String password, String confirmPassword, String tempToken) {
|
||||
private void validateDuplicateEmail(String email, String hubUuid, String roleType) {
|
||||
String beneficiaryRoleType = RoleStatusEnum.ROLE_BENEFICIARY.getValue();
|
||||
|
||||
if (beneficiaryRoleType.equals(roleType)) {
|
||||
Boolean beneficiaryExistsInHub = userRepository.existsByEmailIgnoreCaseForBeneficiaries(
|
||||
email, hubUuid, beneficiaryRoleType);
|
||||
|
||||
if (Boolean.TRUE.equals(beneficiaryExistsInHub)) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
|
||||
}
|
||||
} else {
|
||||
Boolean existsForNonBeneficiaries = userRepository.existsByEmailIgnoreCaseForNonBeneficiaries(
|
||||
email, hubUuid, beneficiaryRoleType);
|
||||
|
||||
if (Boolean.TRUE.equals(existsForNonBeneficiaries)) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void validatePassword(String password, String confirmPassword, String tempToken) {
|
||||
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPassword)) {
|
||||
if(tempToken == null) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.VALIDATE_PASSWORD));
|
||||
@@ -219,7 +275,7 @@ public class UserDao {
|
||||
log.info("Current user details: {}", userEntity);
|
||||
log.info("New user details: {}", userReq);
|
||||
String newStatus = userReq.getStatus() != null ? userReq.getStatus().getValue() : null;
|
||||
if (Boolean.FALSE.equals(userEntity.getStatus().equals(newStatus))) {
|
||||
if (newStatus!=null && Boolean.FALSE.equals(userEntity.getStatus().equals(newStatus))) {
|
||||
userEntity.setStatus(newStatus);
|
||||
}
|
||||
setIfUpdated(userEntity::getFirstName, userEntity::setFirstName, userReq.getFirstName());
|
||||
@@ -228,15 +284,19 @@ public class UserDao {
|
||||
setIfUpdated(userEntity::getAddress, userEntity::setAddress, userReq.getAddress());
|
||||
setIfUpdated(userEntity::getPhoneNumber, userEntity::setPhoneNumber, userReq.getPhoneNumber());
|
||||
setIfUpdated(userEntity::getDateOfBirth, userEntity::setDateOfBirth, userReq.getDateOfBirth());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getCodiceFiscale, userEntity.getBeneficiary()::setCodiceFiscale, userReq.getCodiceFiscale());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getMarketing, userEntity.getBeneficiary()::setMarketing, userReq.getMarketing());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getOffers, userEntity.getBeneficiary()::setOffers, userReq.getOffers());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getThirdParty, userEntity.getBeneficiary()::setThirdParty, userReq.getThirdParty());
|
||||
if (userReq.getRoleId() != null) {
|
||||
RoleEntity roleEntity = roleDao.validateRole(userReq.getRoleId());
|
||||
setIfUpdated(userEntity::getRoleEntity, userEntity::setRoleEntity, roleEntity);
|
||||
if((userEntity.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_INSTRUCTOR_MANAGER.getValue()) && roleEntity.getRoleType().equals(RoleStatusEnum.ROLE_PRE_INSTRUCTOR.getValue())) || (userEntity.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_PRE_INSTRUCTOR.getValue()) && roleEntity.getRoleType().equals(RoleStatusEnum.ROLE_INSTRUCTOR_MANAGER.getValue()))) {
|
||||
setIfUpdated(userEntity::getRoleEntity, userEntity::setRoleEntity, roleEntity);
|
||||
}
|
||||
}
|
||||
if(userEntity.getBeneficiary()!=null) {
|
||||
setIfUpdated(userEntity.getBeneficiary()::getCodiceFiscale, userEntity.getBeneficiary()::setCodiceFiscale, userReq.getCodiceFiscale());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getMarketing, userEntity.getBeneficiary()::setMarketing, userReq.getMarketing());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getOffers, userEntity.getBeneficiary()::setOffers, userReq.getOffers());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getThirdParty, userEntity.getBeneficiary()::setThirdParty, userReq.getThirdParty());
|
||||
setIfUpdated(userEntity.getBeneficiary()::getEmailPec, userEntity.getBeneficiary()::setEmailPec, userReq.getEmailPec());
|
||||
}
|
||||
setIfUpdated(userEntity.getBeneficiary()::getEmailPec, userEntity.getBeneficiary()::setEmailPec, userReq.getEmailPec());
|
||||
userEntity = userRepository.save(userEntity);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Update user details" operation **/
|
||||
@@ -263,7 +323,7 @@ public class UserDao {
|
||||
userEntity.setAddress(userReq.getAddress());
|
||||
userEntity.setPhoneNumber(userReq.getPhoneNumber());
|
||||
userEntity.setDateOfBirth(userReq.getDateOfBirth());
|
||||
}
|
||||
}
|
||||
return userRepository.save(userEntity);
|
||||
}
|
||||
|
||||
@@ -362,25 +422,83 @@ public class UserDao {
|
||||
return user;
|
||||
}
|
||||
|
||||
public String initiatePasswordReset(InitiatePasswordResetReq resetReq) {
|
||||
UserEntity user = userRepository
|
||||
.findByEmailIgnoreCaseAndHubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
public void initiatePasswordReset(InitiatePasswordResetReq resetReq) {
|
||||
UserEntity user = userRepository.findUserExcludingRoleType(
|
||||
resetReq.getEmail(),
|
||||
resetReq.getHubUuid(),
|
||||
RoleStatusEnum.ROLE_BENEFICIARY.getValue()
|
||||
).orElseThrow(() -> new ResourceNotFoundException(
|
||||
Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)
|
||||
));
|
||||
|
||||
UserEntity oldUserEntity = Utils.getClonedEntityForData(user);
|
||||
String token = Utils.generateSecureToken();
|
||||
user.setResetPasswordToken(token);
|
||||
userRepository.save(user);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Initiate password reset request" operation **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldUserEntity).newData(user).build());
|
||||
|
||||
log.info("Password reset token generated for user: {}", resetReq.getEmail());
|
||||
return token;
|
||||
|
||||
sendResetPasswordTokenEmail(user, token);
|
||||
}
|
||||
public void sendResetPasswordTokenEmail(UserEntity user, String token) {
|
||||
|
||||
SystemEmailTemplateResponse emailTemplate = systemEmailTemplatesService.retrieveTemplateByTypeAndCall(
|
||||
SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.PASSWORD_RESET, user.getHub(), null);
|
||||
String redirectUrl = feBaseUrl;
|
||||
if (Boolean.FALSE.equals(StringUtils.isEmpty(user.getHub().getDomainName()))) {
|
||||
redirectUrl = user.getHub().getDomainName();
|
||||
}
|
||||
|
||||
EmailLogRequest emailLogRequest = emailLogDao.createEmailLogRequest(
|
||||
emailTemplate.getEmailScenario(),
|
||||
RecipientTypeEnum.USER,
|
||||
user.getId(),
|
||||
user.getEmail(),
|
||||
user.getId(),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
redirectUrl = String.format(
|
||||
user.getHub().getDomainName() + GepafinConstant.RESET_PASSWORD_URL_FORMAT,
|
||||
token,
|
||||
user.getEmail()
|
||||
);
|
||||
String firstName = user.getFirstName() != null ? user.getFirstName() : "";
|
||||
String lastName = user.getLastName() != null ? user.getLastName() : "";
|
||||
String userName = String.join(" ", firstName, lastName).trim();
|
||||
String subject = Utils.replacePlaceholders(emailTemplate.getSubject(), Map.of(
|
||||
"{{user_name}}", userName
|
||||
));
|
||||
String body = Utils.replacePlaceholders(emailTemplate.getHtmlContent(), Map.of(
|
||||
"{{user_name}}", userName,
|
||||
"{{reset_password_link}}", redirectUrl
|
||||
));
|
||||
emailNotificationDao.sendMail(
|
||||
user.getHub().getId(),
|
||||
subject,
|
||||
body,
|
||||
List.of(user.getEmail()),
|
||||
emailLogRequest
|
||||
);
|
||||
|
||||
log.info("Password reset token email sent to: {}", user.getEmail());
|
||||
}
|
||||
|
||||
public Boolean resetPassword(ResetPasswordReq resetPasswordReq) {
|
||||
UserEntity user = userRepository
|
||||
.findByEmailIgnoreCaseAndHubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
|
||||
UserEntity user = userRepository.findUserExcludingRoleType(
|
||||
resetPasswordReq.getEmail(),
|
||||
resetPasswordReq.getHubUuid(),
|
||||
RoleStatusEnum.ROLE_BENEFICIARY.getValue()
|
||||
).orElseThrow(() -> new ResourceNotFoundException(
|
||||
Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)
|
||||
));
|
||||
|
||||
UserEntity oldUserEntity = Utils.getClonedEntityForData(user);
|
||||
if (!resetPasswordReq.getNewPassword().equals(resetPasswordReq.getConfirmPassword())) {
|
||||
log.info("User creation failed: Passwords do not match for email {}", user.getEmail());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
|
||||
@@ -395,25 +513,36 @@ public class UserDao {
|
||||
user.setPassword(passwordEncoder.encode(resetPasswordReq.getNewPassword()));
|
||||
user.setResetPasswordToken(null);
|
||||
userRepository.save(user);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Reset Password " operation **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldUserEntity).newData(user).build());
|
||||
|
||||
log.info("Password successfully reset for user: {}", resetPasswordReq.getEmail());
|
||||
return true;
|
||||
}
|
||||
|
||||
public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest request) {
|
||||
public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest changePasswordRequest) {
|
||||
UserEntity user = userRepository
|
||||
.findByEmailIgnoreCaseAndHubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
|
||||
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
.findUserExcludingRoleType(changePasswordRequest.getEmail(), userEntity.getHub().getUniqueUuid(),RoleStatusEnum.ROLE_BENEFICIARY.getValue())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(
|
||||
Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)
|
||||
));
|
||||
UserEntity oldUserEntity = Utils.getClonedEntityForData(userEntity);
|
||||
if (!passwordEncoder.matches(changePasswordRequest.getPassword(), user.getPassword())) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CURRENT_PASSWORD_INCORRECT));
|
||||
}
|
||||
if (!request.getNewPassword().equals(request.getConfirmPassword())) {
|
||||
if (!changePasswordRequest.getNewPassword().equals(changePasswordRequest.getConfirmPassword())) {
|
||||
log.info("User creation failed: Passwords do not match for email {}", user.getEmail());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
|
||||
}
|
||||
user.setPassword(passwordEncoder.encode(request.getNewPassword()));
|
||||
user.setPassword(passwordEncoder.encode(changePasswordRequest.getNewPassword()));
|
||||
userRepository.save(user);
|
||||
|
||||
/** This code is responsible for adding a version history log for the "Change user password" operation **/
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldUserEntity).newData(user).build());
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
public void logout(HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
@@ -4,15 +4,11 @@ import feign.FeignException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.enums.UserActionContextEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserActionLogsEnum;
|
||||
import net.gepafin.tendermanagement.model.request.UserActionRequest;
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
import net.gepafin.tendermanagement.model.response.VatCheckResponseBean;
|
||||
import net.gepafin.tendermanagement.service.feignClient.VatCheckService;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -49,10 +45,13 @@ public class VatCheckDao {
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
public Map<String, Object> checkVatNumberApi(String vatNumber) {
|
||||
|
||||
public VatCheckResponseBean checkVatNumberApi(String vatNumber) {
|
||||
VatCheckResponseBean vatCheckResponseBean = new VatCheckResponseBean();
|
||||
vatCheckResponseBean.setValid(false);
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
if (Boolean.TRUE.equals(Boolean.parseBoolean(isVatCheckGloballyDisabled))) {
|
||||
return new HashMap<>();
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
return vatCheckResponseBean;
|
||||
}
|
||||
Map<String, Object> responseBody = new HashMap<>();
|
||||
try {
|
||||
@@ -69,30 +68,57 @@ public class VatCheckDao {
|
||||
if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
|
||||
log.info("Successfully checked vat number");
|
||||
Map<String, Object> responseMap = response.getBody();
|
||||
if (responseMap != null && responseMap.containsKey("data")) {
|
||||
responseBody = (Map<String, Object>) responseMap.get("data");
|
||||
responseBody.remove("timestamp_creation");
|
||||
responseBody.remove("timestamp_last_update");
|
||||
responseBody.remove("data_iscrizione");
|
||||
responseBody.remove("id");
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("data", responseBody);
|
||||
return data;
|
||||
}
|
||||
processValidResponse(responseMap, vatCheckResponseBean);
|
||||
}
|
||||
} catch (FeignException ex) {
|
||||
log.error("Exception occurred while checking vat number: {0}", ex);
|
||||
Utils.callException(ex.status(), ex);
|
||||
if (ex.status() == 406) {
|
||||
try {
|
||||
Map<String, Object> errorResponse = Utils.parseErrorResponse(ex.contentUTF8());
|
||||
processValidResponse(errorResponse, vatCheckResponseBean);
|
||||
} catch (Exception parseEx) {
|
||||
log.error("Failed to parse 406 error response: {0}", parseEx);
|
||||
}
|
||||
} else {
|
||||
log.error("Exception occurred while checking vat number: {0}", ex);
|
||||
Utils.callException(ex.status(), ex);
|
||||
}
|
||||
}
|
||||
return vatCheckResponseBean;
|
||||
}
|
||||
public static void processValidResponse(Map<String, Object> responseMap, VatCheckResponseBean vatCheckResponseBean) {
|
||||
if (responseMap != null && responseMap.containsKey("data")) {
|
||||
Map<String, Object> responseBody = (Map<String, Object>) responseMap.get("data");
|
||||
|
||||
if (responseBody != null) {
|
||||
responseBody.remove("timestamp_creation");
|
||||
responseBody.remove("timestamp_last_update");
|
||||
responseBody.remove("data_iscrizione");
|
||||
responseBody.remove("id");
|
||||
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("data", responseBody);
|
||||
|
||||
vatCheckResponseBean.setValid(true);
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.VALID_VATNUMBER_MSG));
|
||||
vatCheckResponseBean.setVatCheckResponse(data);
|
||||
} else {
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
}
|
||||
} else {
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
}
|
||||
return responseBody;
|
||||
}
|
||||
|
||||
public Map<String, Object> checkVatNumber(String vatNumber) {
|
||||
public VatCheckResponseBean checkVatNumber(String vatNumber) {
|
||||
try {
|
||||
return checkVatNumberApi(vatNumber);
|
||||
} catch (Exception e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
log.error("Error in checkVatNumber: {}", e.getMessage());
|
||||
VatCheckResponseBean vatCheckResponseBean = new VatCheckResponseBean();
|
||||
vatCheckResponseBean.setValid(false);
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
return vatCheckResponseBean;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user