Merge branch 'develop' of https://github.com/Kitzanos/GEPAFIN-BE into feature/GEPAFINBE-199
This commit is contained in:
@@ -134,6 +134,12 @@ public class ApplicationAmendmentRequestDao {
|
||||
@Autowired
|
||||
private ApplicationEvaluationFormRepository applicationEvaluationFormRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationAmendmentRequestViewRepository applicationAmendmentRequestViewRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationDao applicationDao;
|
||||
|
||||
public ApplicationAmendmentRequestResponse getApplicationDataForAmendment(Long applicationEvaluationId) {
|
||||
log.info("Fetching the application data for the Amendment process {}", applicationEvaluationId);
|
||||
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluation(applicationEvaluationId);
|
||||
@@ -1268,7 +1274,122 @@ public class ApplicationAmendmentRequestDao {
|
||||
documentService.deleteFile(documentId);
|
||||
}
|
||||
|
||||
public PageableResponseBean<List<ApplicationAmendmentRequestResponse>> getApplicationAmendmentByPaginnation(Long userId, ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
|
||||
// public PageableResponseBean<List<ApplicationAmendmentRequestResponse>> getApplicationAmendmentByPaginnation(Long userId, ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
|
||||
// Integer pageNo = null;
|
||||
// Integer pageLimit = null;
|
||||
// if (applicationAmendmentPaginationRequestBean.getGlobalFilters() != null) {
|
||||
// pageNo = applicationAmendmentPaginationRequestBean.getGlobalFilters().getPage();
|
||||
// pageLimit = applicationAmendmentPaginationRequestBean.getGlobalFilters().getLimit();
|
||||
// }
|
||||
// if (pageLimit == null || pageLimit <= 0) {
|
||||
// pageLimit = GepafinConstant.DEFAULT_PAGE_LIMIT;
|
||||
// }
|
||||
// if (pageNo == null || pageNo <= 0) {
|
||||
// pageNo = GepafinConstant.DEFAULT_PAGE;
|
||||
// }
|
||||
// Specification<ApplicationAmendmentRequestEntity> spec = searchPagination(userId,applicationAmendmentPaginationRequestBean);
|
||||
// Page<ApplicationAmendmentRequestEntity> entityPage = applicationAmendmentRequestRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
|
||||
//
|
||||
//
|
||||
// List<ApplicationAmendmentRequestResponse> applicationResponses = entityPage.getContent().stream()
|
||||
// .map(application -> {
|
||||
// ApplicationAmendmentRequestResponse response = convertEntityToResponse(application,false);
|
||||
// return response;
|
||||
// })
|
||||
// .collect(Collectors.toList());
|
||||
//
|
||||
//
|
||||
// PageableResponseBean<List<ApplicationAmendmentRequestResponse>> pageableResponseBean = new PageableResponseBean<>();
|
||||
// pageableResponseBean.setBody(applicationResponses);
|
||||
// pageableResponseBean.setCurrentPage(entityPage.getNumber() + 1); // Page numbers typically start from 0, so add 1 for user-friendly indexing
|
||||
// pageableResponseBean.setTotalPages(entityPage.getTotalPages());
|
||||
// pageableResponseBean.setTotalRecords(entityPage.getTotalElements());
|
||||
// pageableResponseBean.setPageSize(entityPage.getSize());
|
||||
//
|
||||
// return pageableResponseBean;
|
||||
// }
|
||||
//
|
||||
// public Specification<ApplicationAmendmentRequestEntity> searchPagination(Long userId,ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
|
||||
// return (root, query, criteriaBuilder) -> {
|
||||
//
|
||||
// List<Predicate> predicates = getPredicates(applicationAmendmentPaginationRequestBean, criteriaBuilder, root,userId);
|
||||
// SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
|
||||
//
|
||||
// if (applicationAmendmentPaginationRequestBean .getGlobalFilters() != null
|
||||
// && applicationAmendmentPaginationRequestBean.getGlobalFilters().getSortBy() != null &&
|
||||
// applicationAmendmentPaginationRequestBean.getGlobalFilters().getSortBy().getColumnName() != null && Boolean.FALSE.equals(
|
||||
// isEmpty(applicationAmendmentPaginationRequestBean.getGlobalFilters().getSortBy().getColumnName()))) {
|
||||
// sortBy.setColumnName(applicationAmendmentPaginationRequestBean.getGlobalFilters().getSortBy().getColumnName());
|
||||
// sortBy.setSortDesc(true);
|
||||
// if (applicationAmendmentPaginationRequestBean.getGlobalFilters().getSortBy().getSortDesc() != null) {
|
||||
// sortBy.setSortDesc(applicationAmendmentPaginationRequestBean.getGlobalFilters().getSortBy().getSortDesc());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// query.orderBy(criteriaBuilder.desc(root.get(sortBy.getColumnName())));
|
||||
// if (Boolean.FALSE.equals(sortBy.getSortDesc())) {
|
||||
// query.orderBy(criteriaBuilder.asc(root.get(sortBy.getColumnName())));
|
||||
// }
|
||||
// return query.where(criteriaBuilder.and(predicates.toArray(new Predicate[0]))).getRestriction();
|
||||
// };
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private List<Predicate> getPredicates(ApplicationAmendmentPaginationRequestBean amendmentPaginationRequestBean,
|
||||
// CriteriaBuilder criteriaBuilder, Root<ApplicationAmendmentRequestEntity> root,Long userId) {
|
||||
//
|
||||
// Integer year = null;
|
||||
// String search = null;
|
||||
// if (amendmentPaginationRequestBean.getGlobalFilters() != null) {
|
||||
// year = amendmentPaginationRequestBean.getGlobalFilters().getYear();
|
||||
// search = amendmentPaginationRequestBean.getGlobalFilters().getSearch();
|
||||
// }
|
||||
// List<Predicate> predicates = new ArrayList<>();
|
||||
//
|
||||
// if (year != null && year > 0) {
|
||||
// int filterYear = amendmentPaginationRequestBean.getGlobalFilters().getYear();
|
||||
//
|
||||
//// Create LocalDateTime boundaries for the start and end of the year
|
||||
// LocalDateTime startOfYear = LocalDateTime.of(filterYear, 1, 1, 0, 0);
|
||||
// LocalDateTime endOfYear = LocalDateTime.of(filterYear, 12, 31, 23, 59, 59);
|
||||
//
|
||||
//// Add the range comparison to filter records within the year
|
||||
// predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), startOfYear, endOfYear));
|
||||
//
|
||||
// }
|
||||
// // Search in `title` and `message` (if search term is provided)
|
||||
// if (search != null && !search.isEmpty()) {
|
||||
// Predicate notePredicate = criteriaBuilder.like(
|
||||
// criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
|
||||
// "%" + search.toUpperCase() + "%"
|
||||
// );
|
||||
// predicates.add(criteriaBuilder.or(notePredicate));
|
||||
// Predicate internalNotePredicate = criteriaBuilder.like(
|
||||
// criteriaBuilder.upper(root.get(GepafinConstant.INTERNAL_NOTE)),
|
||||
// "%" + search.toUpperCase() + "%"
|
||||
// );
|
||||
// predicates.add(criteriaBuilder.or(internalNotePredicate));
|
||||
// }
|
||||
//
|
||||
// // Filter by `status` (if status list is provided)
|
||||
// if (amendmentPaginationRequestBean.getStatus() != null && !amendmentPaginationRequestBean.getStatus().isEmpty()) {
|
||||
// List<String> statusValues = amendmentPaginationRequestBean.getStatus().stream()
|
||||
// .map(ApplicationAmendmentRequestEnum::name) // Convert enum to string
|
||||
// .toList();
|
||||
// predicates.add(root.get(GepafinConstant.STATUS).in(statusValues));
|
||||
// }
|
||||
// if(Boolean.TRUE.equals(validator.checkIsBeneficiary()) || Boolean.TRUE.equals(validator.checkIsConfidi())) {
|
||||
// predicates.add(root.get("applicationEvaluationEntity").get("assignedApplicationsEntity").get("application").get("userId").in(userId));
|
||||
// }
|
||||
// else {
|
||||
// predicates.add(root.get("applicationEvaluationEntity").get("assignedApplicationsEntity").get("userId").in(userId));
|
||||
// }
|
||||
//
|
||||
// return predicates;
|
||||
//
|
||||
// }
|
||||
|
||||
public PageableResponseBean<List<ApplicationAmendmentRequestViewResponse>> getApplicationAmendmentByPaginationByView(Long userId, ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
|
||||
Integer pageNo = null;
|
||||
Integer pageLimit = null;
|
||||
if (applicationAmendmentPaginationRequestBean.getGlobalFilters() != null) {
|
||||
@@ -1281,20 +1402,20 @@ public class ApplicationAmendmentRequestDao {
|
||||
if (pageNo == null || pageNo <= 0) {
|
||||
pageNo = GepafinConstant.DEFAULT_PAGE;
|
||||
}
|
||||
Specification<ApplicationAmendmentRequestEntity> spec = searchPagination(userId,applicationAmendmentPaginationRequestBean);
|
||||
Page<ApplicationAmendmentRequestEntity> entityPage = applicationAmendmentRequestRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
|
||||
Specification<ApplicationAmendmentRequestView> spec = searchPaginationByView(userId,applicationAmendmentPaginationRequestBean);
|
||||
Page<ApplicationAmendmentRequestView> entityPage = applicationAmendmentRequestViewRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
|
||||
|
||||
|
||||
List<ApplicationAmendmentRequestResponse> applicationResponses = entityPage.getContent().stream()
|
||||
.map(application -> {
|
||||
ApplicationAmendmentRequestResponse response = convertEntityToResponse(application,false);
|
||||
List<ApplicationAmendmentRequestViewResponse> applicationAmendmentRequestViewResponses = entityPage.getContent().stream()
|
||||
.map(amendmentRequestView -> {
|
||||
ApplicationAmendmentRequestViewResponse response = convertAmendmentEntityToApplicationAmendmentRequestViewResponse(amendmentRequestView);
|
||||
return response;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
|
||||
PageableResponseBean<List<ApplicationAmendmentRequestResponse>> pageableResponseBean = new PageableResponseBean<>();
|
||||
pageableResponseBean.setBody(applicationResponses);
|
||||
PageableResponseBean<List<ApplicationAmendmentRequestViewResponse>> pageableResponseBean = new PageableResponseBean<>();
|
||||
pageableResponseBean.setBody(applicationAmendmentRequestViewResponses);
|
||||
pageableResponseBean.setCurrentPage(entityPage.getNumber() + 1); // Page numbers typically start from 0, so add 1 for user-friendly indexing
|
||||
pageableResponseBean.setTotalPages(entityPage.getTotalPages());
|
||||
pageableResponseBean.setTotalRecords(entityPage.getTotalElements());
|
||||
@@ -1302,11 +1423,10 @@ public class ApplicationAmendmentRequestDao {
|
||||
|
||||
return pageableResponseBean;
|
||||
}
|
||||
|
||||
public Specification<ApplicationAmendmentRequestEntity> searchPagination(Long userId,ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
|
||||
public Specification<ApplicationAmendmentRequestView> searchPaginationByView(Long userId,ApplicationAmendmentPaginationRequestBean applicationAmendmentPaginationRequestBean) {
|
||||
return (root, query, criteriaBuilder) -> {
|
||||
|
||||
List<Predicate> predicates = getPredicates(applicationAmendmentPaginationRequestBean, criteriaBuilder, root,userId);
|
||||
List<Predicate> predicates = getPredicatesByView(applicationAmendmentPaginationRequestBean, criteriaBuilder, root,userId);
|
||||
SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
|
||||
|
||||
if (applicationAmendmentPaginationRequestBean .getGlobalFilters() != null
|
||||
@@ -1329,15 +1449,19 @@ public class ApplicationAmendmentRequestDao {
|
||||
}
|
||||
|
||||
|
||||
private List<Predicate> getPredicates(ApplicationAmendmentPaginationRequestBean amendmentPaginationRequestBean,
|
||||
CriteriaBuilder criteriaBuilder, Root<ApplicationAmendmentRequestEntity> root,Long userId) {
|
||||
private List<Predicate> getPredicatesByView(ApplicationAmendmentPaginationRequestBean amendmentPaginationRequestBean,
|
||||
CriteriaBuilder criteriaBuilder, Root<ApplicationAmendmentRequestView> root,Long userId) {
|
||||
|
||||
Integer year = null;
|
||||
String search = null;
|
||||
Map<String, FilterCriteria> filters = new HashMap<>();
|
||||
if (amendmentPaginationRequestBean.getGlobalFilters() != null) {
|
||||
year = amendmentPaginationRequestBean.getGlobalFilters().getYear();
|
||||
search = amendmentPaginationRequestBean.getGlobalFilters().getSearch();
|
||||
}
|
||||
if (amendmentPaginationRequestBean.getFilters() != null) {
|
||||
filters = amendmentPaginationRequestBean.getFilters();
|
||||
}
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
|
||||
if (year != null && year > 0) {
|
||||
@@ -1351,19 +1475,37 @@ public class ApplicationAmendmentRequestDao {
|
||||
predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), startOfYear, endOfYear));
|
||||
|
||||
}
|
||||
// Search in `title` and `message` (if search term is provided)
|
||||
|
||||
if (search != null && !search.isEmpty()) {
|
||||
Predicate notePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
|
||||
List<Predicate> searchPredicates = new ArrayList<>();
|
||||
|
||||
searchPredicates.add(criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.CALL_NAME)),
|
||||
"%" + search.toUpperCase() + "%"
|
||||
);
|
||||
predicates.add(criteriaBuilder.or(notePredicate));
|
||||
Predicate internalNotePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.INTERNAL_NOTE)),
|
||||
));
|
||||
|
||||
searchPredicates.add(criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.COMPANY_NAME)),
|
||||
"%" + search.toUpperCase() + "%"
|
||||
);
|
||||
predicates.add(criteriaBuilder.or(internalNotePredicate));
|
||||
));
|
||||
|
||||
// Uncomment these if needed
|
||||
// searchPredicates.add(criteriaBuilder.like(
|
||||
// criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
|
||||
// "%" + search.toUpperCase() + "%"
|
||||
// ));
|
||||
//
|
||||
// searchPredicates.add(criteriaBuilder.like(
|
||||
// criteriaBuilder.upper(root.get(GepafinConstant.INTERNAL_NOTE)),
|
||||
// "%" + search.toUpperCase() + "%"
|
||||
// ));
|
||||
|
||||
Predicate finalPredicate = criteriaBuilder.or(searchPredicates.toArray(new Predicate[0]));
|
||||
|
||||
predicates.add(finalPredicate);
|
||||
}
|
||||
Utils.applyFiltersByPagination(root, criteriaBuilder, predicates, filters);
|
||||
|
||||
|
||||
// Filter by `status` (if status list is provided)
|
||||
if (amendmentPaginationRequestBean.getStatus() != null && !amendmentPaginationRequestBean.getStatus().isEmpty()) {
|
||||
@@ -1372,14 +1514,33 @@ public class ApplicationAmendmentRequestDao {
|
||||
.toList();
|
||||
predicates.add(root.get(GepafinConstant.STATUS).in(statusValues));
|
||||
}
|
||||
if(Boolean.TRUE.equals(validator.checkIsBeneficiary()) || Boolean.TRUE.equals(validator.checkIsConfidi())) {
|
||||
predicates.add(root.get("applicationEvaluationEntity").get("assignedApplicationsEntity").get("application").get("userId").in(userId));
|
||||
}
|
||||
else {
|
||||
predicates.add(root.get("applicationEvaluationEntity").get("assignedApplicationsEntity").get("userId").in(userId));
|
||||
boolean isBeneficiaryOrConfidi = validator.checkIsBeneficiary() || validator.checkIsConfidi();
|
||||
boolean isPreInstructor = validator.checkIsPreInstructor();
|
||||
boolean isInstructorManagerWithPersonalRecords = validator.checkIsInstructorManager() &&
|
||||
Boolean.TRUE.equals(amendmentPaginationRequestBean.getPersonalRecords());
|
||||
|
||||
if (isBeneficiaryOrConfidi) {
|
||||
predicates.add(root.get(GepafinConstant.APPLICATION_USER_ID).in(userId));
|
||||
} else if (isPreInstructor || isInstructorManagerWithPersonalRecords) {
|
||||
predicates.add(root.get(GepafinConstant.ASSIGNED_USER_ID).in(userId));
|
||||
}
|
||||
|
||||
return predicates;
|
||||
|
||||
}
|
||||
public ApplicationAmendmentRequestViewResponse convertAmendmentEntityToApplicationAmendmentRequestViewResponse(ApplicationAmendmentRequestView applicationAmendmentRequestView){
|
||||
ApplicationAmendmentRequestViewResponse applicationAmendmentRequestViewResponse=new ApplicationAmendmentRequestViewResponse();
|
||||
applicationAmendmentRequestViewResponse.setId(applicationAmendmentRequestView.getId());
|
||||
applicationAmendmentRequestViewResponse.setApplicationId(applicationAmendmentRequestView.getApplicationId());
|
||||
applicationAmendmentRequestViewResponse.setProtocolNumber(applicationAmendmentRequestView.getProtocolNumber());
|
||||
applicationAmendmentRequestViewResponse.setCallName(applicationAmendmentRequestView.getCallName());
|
||||
applicationAmendmentRequestViewResponse.setCompanyName(applicationAmendmentRequestView.getCompanyName());
|
||||
applicationAmendmentRequestViewResponse.setStartDate(applicationAmendmentRequestView.getStartDate());
|
||||
applicationAmendmentRequestViewResponse.setExpirationDate(applicationAmendmentRequestView.getExpirationDate());
|
||||
applicationAmendmentRequestViewResponse.setAssigendUserName(applicationAmendmentRequestView.getAssigendUserName());
|
||||
applicationAmendmentRequestViewResponse.setStatus(applicationAmendmentRequestView.getStatus());
|
||||
return applicationAmendmentRequestViewResponse;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -21,15 +21,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;
|
||||
@@ -47,9 +46,14 @@ 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.text.MessageFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -185,6 +189,11 @@ public class ApplicationDao {
|
||||
@Autowired
|
||||
private ApplicationViewRepository applicationViewRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationFormViewRepository applicationFormViewRepository;
|
||||
|
||||
@Autowired
|
||||
private FormRepository formRepository;
|
||||
|
||||
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
|
||||
FormEntity formEntity = formService.validateForm(formId);
|
||||
@@ -1438,185 +1447,6 @@ public class ApplicationDao {
|
||||
}
|
||||
}
|
||||
|
||||
public PageableResponseBean<List<ApplicationResponse>> getAllApplicationByPagination(UserEntity userEntity, Long callId, Long companyId, ApplicationPageableRequestBean applicationPageableRequestBean) {
|
||||
Integer pageNo = null;
|
||||
Integer pageLimit = null;
|
||||
|
||||
UserWithCompanyEntity userWithCompany= userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), companyId).orElse(null);
|
||||
Long userWithCompanyId = userWithCompany!=null?userWithCompany.getId():null;
|
||||
if (applicationPageableRequestBean.getGlobalFilters() != null) {
|
||||
pageNo = applicationPageableRequestBean.getGlobalFilters().getPage();
|
||||
pageLimit = applicationPageableRequestBean.getGlobalFilters().getLimit();
|
||||
}
|
||||
if (pageLimit == null || pageLimit <= 0) {
|
||||
pageLimit = GepafinConstant.DEFAULT_PAGE_LIMIT;
|
||||
}
|
||||
if (pageNo == null || pageNo <= 0) {
|
||||
pageNo = GepafinConstant.DEFAULT_PAGE;
|
||||
}
|
||||
Specification<ApplicationEntity> spec = search(callId,companyId, userWithCompanyId, applicationPageableRequestBean, userEntity);
|
||||
Page<ApplicationEntity> entityPage = applicationRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
|
||||
// Prepare the response
|
||||
|
||||
|
||||
List<ApplicationResponse> applicationResponses = entityPage.getContent().stream()
|
||||
.map(application -> {
|
||||
ApplicationResponse response = getApplicationResponse(application);
|
||||
return response;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
|
||||
PageableResponseBean<List<ApplicationResponse>> pageableResponseBean = new PageableResponseBean<>();
|
||||
pageableResponseBean.setBody(applicationResponses);
|
||||
pageableResponseBean.setCurrentPage(entityPage.getNumber() + 1); // Page numbers typically start from 0, so add 1 for user-friendly indexing
|
||||
pageableResponseBean.setTotalPages(entityPage.getTotalPages());
|
||||
pageableResponseBean.setTotalRecords(entityPage.getTotalElements());
|
||||
pageableResponseBean.setPageSize(entityPage.getSize());
|
||||
|
||||
return pageableResponseBean;
|
||||
}
|
||||
|
||||
public Specification<ApplicationEntity> search(Long callId, Long companyId, Long userWithCompanyId, ApplicationPageableRequestBean applicationPageableRequestBean, UserEntity userEntity) {
|
||||
return (root, query, criteriaBuilder) -> {
|
||||
|
||||
List<Predicate> predicates = getPredicates(applicationPageableRequestBean, criteriaBuilder, root, callId,companyId, userWithCompanyId, userEntity);
|
||||
SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
|
||||
|
||||
if (applicationPageableRequestBean.getGlobalFilters() != null
|
||||
&& applicationPageableRequestBean.getGlobalFilters().getSortBy() != null &&
|
||||
applicationPageableRequestBean.getGlobalFilters().getSortBy().getColumnName() != null && Boolean.FALSE.equals(
|
||||
isEmpty(applicationPageableRequestBean.getGlobalFilters().getSortBy().getColumnName()))) {
|
||||
sortBy.setColumnName(applicationPageableRequestBean.getGlobalFilters().getSortBy().getColumnName());
|
||||
sortBy.setSortDesc(true);
|
||||
if (applicationPageableRequestBean.getGlobalFilters().getSortBy().getSortDesc() != null) {
|
||||
sortBy.setSortDesc(applicationPageableRequestBean.getGlobalFilters().getSortBy().getSortDesc());
|
||||
}
|
||||
}
|
||||
|
||||
query.orderBy(criteriaBuilder.desc(root.get(sortBy.getColumnName())));
|
||||
if (Boolean.FALSE.equals(sortBy.getSortDesc())) {
|
||||
query.orderBy(criteriaBuilder.asc(root.get(sortBy.getColumnName())));
|
||||
}
|
||||
return query.where(criteriaBuilder.and(predicates.toArray(new Predicate[0]))).getRestriction();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private List<Predicate> getPredicates(ApplicationPageableRequestBean applicationPageableRequestBean,
|
||||
CriteriaBuilder criteriaBuilder, Root<ApplicationEntity> root, Long callId,Long companyId, Long userWithCompanyId, UserEntity userEntity) {
|
||||
|
||||
Integer year = null;
|
||||
String search = null;
|
||||
Integer daysRange = null;
|
||||
Map<String, FilterCriteria> filters = new HashMap<>();
|
||||
if (applicationPageableRequestBean.getGlobalFilters() != null) {
|
||||
year = applicationPageableRequestBean.getGlobalFilters().getYear();
|
||||
search = applicationPageableRequestBean.getGlobalFilters().getSearch();
|
||||
daysRange = applicationPageableRequestBean.getDaysRange();
|
||||
}
|
||||
if (applicationPageableRequestBean.getFilters() != null) {
|
||||
filters = applicationPageableRequestBean.getFilters();
|
||||
}
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
|
||||
// Boolean isBeneficiary = validator.checkIsBeneficiary();
|
||||
if (Boolean.TRUE.equals(validator.checkIsBeneficiary()) || Boolean.TRUE.equals(validator.checkIsConfidi())) {
|
||||
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.USER_ID), userEntity.getId()));
|
||||
}
|
||||
if (year != null && year > 0) {
|
||||
int filterYear = applicationPageableRequestBean.getGlobalFilters().getYear();
|
||||
|
||||
// Create LocalDateTime boundaries for the start and end of the year
|
||||
LocalDateTime startOfYear = LocalDateTime.of(filterYear, 1, 1, 0, 0);
|
||||
LocalDateTime endOfYear = LocalDateTime.of(filterYear, 12, 31, 23, 59, 59);
|
||||
|
||||
// Add the range comparison to filter records within the year
|
||||
predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), startOfYear, endOfYear));
|
||||
|
||||
}
|
||||
// Search in `title` and `message` (if search term is provided)
|
||||
if (search != null && !search.isEmpty()) {
|
||||
Predicate titlePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.COMMENTS)),
|
||||
"%" + search.toUpperCase() + "%"
|
||||
);
|
||||
// Predicate protocolPredicate = criteriaBuilder.like(
|
||||
// criteriaBuilder.function(
|
||||
// "TO_CHAR",
|
||||
// String.class,
|
||||
// criteriaBuilder.function("CAST", String.class, root.get(GepafinConstant.PROTOCOL).get(GepafinConstant.PROTOCOL_NUMBER))
|
||||
// ),
|
||||
// "%" + search + "%"
|
||||
// );
|
||||
|
||||
Predicate callNamePredicate =criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.CALL).get(GepafinConstant.NAME)), // Adjust field name
|
||||
"%" + search.toUpperCase() + "%"
|
||||
);
|
||||
|
||||
// predicates.add(criteriaBuilder.or(protocolPredicate));
|
||||
predicates.add(criteriaBuilder.or(callNamePredicate));
|
||||
predicates.add(criteriaBuilder.or(titlePredicate));
|
||||
}
|
||||
|
||||
// Filter by `status` (if status list is provided)
|
||||
if (applicationPageableRequestBean.getStatus() != null && !applicationPageableRequestBean.getStatus().isEmpty()) {
|
||||
List<String> statusValues = applicationPageableRequestBean.getStatus().stream()
|
||||
.map(ApplicationStatusTypeEnum::name) // Convert enum to string
|
||||
.toList();
|
||||
predicates.add(root.get(GepafinConstant.STATUS).in(statusValues));
|
||||
}
|
||||
|
||||
if (callId != null) {
|
||||
CallEntity call = callService.validateCall(callId);
|
||||
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.CALL).get(GepafinConstant.ID), callId));
|
||||
}
|
||||
|
||||
// Optional companyId filter
|
||||
if (userWithCompanyId != null) {
|
||||
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.USER_WITH_COMPANY).get(GepafinConstant.ID), userWithCompanyId));
|
||||
}
|
||||
if (companyId != null) {
|
||||
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.COMPANY_ID), companyId));
|
||||
}
|
||||
|
||||
if (daysRange != null && daysRange >= 0) {
|
||||
LocalDateTime today = LocalDateTime.now();
|
||||
LocalDateTime pastDate = today.minusDays(daysRange);
|
||||
predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), pastDate, today));
|
||||
}
|
||||
applyFilters(root, criteriaBuilder, predicates, filters);
|
||||
|
||||
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
|
||||
|
||||
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.HUB_ID), userEntity.getHub().getId()));
|
||||
|
||||
|
||||
return predicates;
|
||||
}
|
||||
private void applyFilters(Root<?> root, CriteriaBuilder criteriaBuilder, List<Predicate> predicates, Map<String, FilterCriteria> filters) {
|
||||
if (Boolean.FALSE.equals(filters.isEmpty())) {
|
||||
for (Map.Entry<String, FilterCriteria> entry : filters.entrySet()) {
|
||||
String fieldName = entry.getKey();
|
||||
FilterCriteria filterCriteria = entry.getValue();
|
||||
Object value = filterCriteria.getValue();
|
||||
MatchModeEnum matchMode = filterCriteria.getMatchMode();
|
||||
|
||||
if (value != null && matchMode != null) {
|
||||
Path<?> fieldPath = root.get(fieldName);
|
||||
if (fieldPath != null) {
|
||||
Utils.applyStringFilter(fieldPath, criteriaBuilder, predicates, value, matchMode);
|
||||
Utils.applyNumberFilter(fieldPath, criteriaBuilder, predicates, value, matchMode);
|
||||
Utils.applyDateFilter(fieldPath, criteriaBuilder, predicates, value, matchMode,root);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// private Path<?> getFieldPath(Root<?> root, String fieldName) {
|
||||
// try {
|
||||
@@ -1889,27 +1719,29 @@ public class ApplicationDao {
|
||||
}
|
||||
// Search in `title` and `message` (if search term is provided)
|
||||
if (search != null && !search.isEmpty()) {
|
||||
String searchPattern = "%" + search.toUpperCase() + "%";
|
||||
|
||||
Predicate titlePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.COMMENTS)),
|
||||
"%" + search.toUpperCase() + "%"
|
||||
);
|
||||
// Predicate protocolPredicate = criteriaBuilder.like(
|
||||
// criteriaBuilder.function(
|
||||
// "TO_CHAR",
|
||||
// String.class,
|
||||
// criteriaBuilder.function("CAST", String.class, root.get(GepafinConstant.PROTOCOL).get(GepafinConstant.PROTOCOL_NUMBER))
|
||||
// ),
|
||||
// "%" + search + "%"
|
||||
// );
|
||||
|
||||
Predicate callNamePredicate =criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.CALL_TITLE)), // Adjust field name
|
||||
"%" + search.toUpperCase() + "%"
|
||||
searchPattern
|
||||
);
|
||||
|
||||
// predicates.add(criteriaBuilder.or(protocolPredicate));
|
||||
predicates.add(criteriaBuilder.or(callNamePredicate));
|
||||
predicates.add(criteriaBuilder.or(titlePredicate));
|
||||
Predicate callTitlePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.CALL_TITLE)),
|
||||
searchPattern
|
||||
);
|
||||
Predicate callNamePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.CALL_NAME)),
|
||||
searchPattern
|
||||
);
|
||||
Predicate companyName = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.COMPANY_NAME)),
|
||||
searchPattern
|
||||
);
|
||||
|
||||
// Combine them using a single `or()`
|
||||
Predicate finalPredicate = criteriaBuilder.or(titlePredicate, callTitlePredicate,callNamePredicate,companyName);
|
||||
predicates.add(finalPredicate);
|
||||
}
|
||||
|
||||
// Filter by `status` (if status list is provided)
|
||||
@@ -1938,7 +1770,7 @@ public class ApplicationDao {
|
||||
LocalDateTime pastDate = today.minusDays(daysRange);
|
||||
predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), pastDate, today));
|
||||
}
|
||||
applyFilters(root, criteriaBuilder, predicates, filters);
|
||||
Utils.applyFiltersByPagination(root, criteriaBuilder, predicates, filters);
|
||||
|
||||
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
|
||||
|
||||
@@ -1952,7 +1784,7 @@ public class ApplicationDao {
|
||||
ApplicationResponse responseBean = new ApplicationResponse();
|
||||
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationView.getCallId());
|
||||
Long totalFormSteps = flowFormDao.calculateTotalSteps(flowEdgesList);
|
||||
Long completedSteps= Long.valueOf(flowFormDao.getCompletedStepsByView(applicationView.getId(), false));
|
||||
Long completedSteps = Long.valueOf(flowFormDao.getCompletedStepsByView(applicationView.getId(), false));
|
||||
Integer progress = calculateProgress(totalFormSteps, completedSteps);
|
||||
responseBean.setId(applicationView.getId());
|
||||
responseBean.setProgress(progress);
|
||||
@@ -1966,23 +1798,326 @@ public class ApplicationDao {
|
||||
responseBean.setEvaluationVersion(EvaluationVersionEnum.valueOf(applicationView.getEvaluationVersion()));
|
||||
responseBean.setComments(applicationView.getComments());
|
||||
responseBean.setCompanyId(applicationView.getCompanyId());
|
||||
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
|
||||
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationView.getId());
|
||||
if(assignedApplicationsOptional.isPresent()){
|
||||
responseBean.setAssignedUserId(assignedApplicationsOptional.get().getUserId());
|
||||
UserEntity user = userService.validateUser(assignedApplicationsOptional.get().getUserId());
|
||||
String firstName = user.getFirstName() != null ? user.getFirstName() : "";
|
||||
String lastName = user.getLastName() != null ? user.getLastName() : "";
|
||||
String userName = String.join(" ", firstName, lastName).trim();
|
||||
responseBean.setAssignedUserName(userName);
|
||||
}
|
||||
CompanyEntity company=companyService.validateCompany(applicationView.getCompanyId());
|
||||
responseBean.setCompanyName(company.getCompanyName());
|
||||
responseBean.setProtocolNumber(applicationView.getProtocolNumber());
|
||||
responseBean.setAssignedUserId(applicationView.getAssignedUserId());
|
||||
responseBean.setAssignedUserName(applicationView.getAssignedUserName());
|
||||
responseBean.setCompanyName(applicationView.getCompanyName());
|
||||
responseBean.setProtocolNumber(applicationView.getProtocolNumber());
|
||||
responseBean.setAmountAccepted(applicationView.getAmountAccepted());
|
||||
responseBean.setAmountRequested(applicationView.getAmountRequested());
|
||||
responseBean.setDateAccepted(applicationView.getDateAccepted());
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1665,7 +1665,7 @@ public class ApplicationEvaluationDao {
|
||||
});
|
||||
}
|
||||
|
||||
private String getLabelFromSettings(ContentResponseBean contentResponseBean) {
|
||||
public String getLabelFromSettings(ContentResponseBean contentResponseBean) {
|
||||
String label = contentResponseBean.getLabel();
|
||||
if (contentResponseBean.getSettings() != null) {
|
||||
for (SettingResponseBean setting : contentResponseBean.getSettings()) {
|
||||
|
||||
@@ -96,9 +96,6 @@ public class AppointmentDao {
|
||||
@Value("${aws.s3.bucket.name}")
|
||||
private String OLD_BUCKET;
|
||||
|
||||
@Value("${flagDaFirmare}")
|
||||
private Boolean flagDaFirmare;
|
||||
|
||||
@Autowired
|
||||
private HubRepository hubRepository;
|
||||
|
||||
@@ -963,7 +960,7 @@ public class AppointmentDao {
|
||||
UploadDocToExternalSystemRequest.Input input = new UploadDocToExternalSystemRequest.Input();
|
||||
input.setIdTipoProtocollo(docToExternalSystemRequest.getInput().getIdTipoProtocollo());
|
||||
input.setIdClassificazione(docToExternalSystemRequest.getInput().getIdClassificazione());
|
||||
input.setFlagDaFirmare(flagDaFirmare);
|
||||
input.setFlagDaFirmare(docToExternalSystemRequest.getInput().getFlagDaFirmare());
|
||||
input.setDescrizione(docToExternalSystemRequest.getInput().getDescrizione());
|
||||
|
||||
UploadDocToExternalSystemRequest.Input.Attributes attributes = new UploadDocToExternalSystemRequest.Input.Attributes();
|
||||
|
||||
@@ -14,12 +14,14 @@ import net.gepafin.tendermanagement.model.request.ApplicationEvaluationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.request.UpdateAssignedApplicationRequest;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationViewResponse;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
import net.gepafin.tendermanagement.model.response.PageableResponseBean;
|
||||
import net.gepafin.tendermanagement.model.util.SortBy;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationEvaluationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
|
||||
import net.gepafin.tendermanagement.repositories.AssignedApplicationsViewRepository;
|
||||
import net.gepafin.tendermanagement.service.ApplicationService;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
@@ -77,6 +79,9 @@ public class AssignedApplicationsDao {
|
||||
@Autowired
|
||||
private ApplicationEvaluationRepository applicationEvaluationRepository;
|
||||
|
||||
@Autowired
|
||||
private AssignedApplicationsViewRepository assignedApplicationsViewRepository;
|
||||
|
||||
public AssignedApplicationsResponse createAssignedApplications(Long applicationId, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest) {
|
||||
log.info("Assigning application to pre-Instructor with details: {}", applicationId, userId);
|
||||
|
||||
@@ -297,7 +302,7 @@ public class AssignedApplicationsDao {
|
||||
log.info("Assigned application fetched successfully: {}", response);
|
||||
return response;
|
||||
}
|
||||
public PageableResponseBean<List<AssignedApplicationsResponse>> getAllAssignedApplicationsByPagination(UserEntity user, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,Long userId) {
|
||||
public PageableResponseBean<List<AssignedApplicationViewResponse>> getAllAssignedApplicationsByPagination(UserEntity user, AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,Long userId) {
|
||||
Integer pageNo = null;
|
||||
Integer pageLimit = null;
|
||||
if (assignedApplicationPageableRequestBean.getGlobalFilters() != null) {
|
||||
@@ -310,21 +315,15 @@ public class AssignedApplicationsDao {
|
||||
if (pageNo == null || pageNo <= 0) {
|
||||
pageNo = GepafinConstant.DEFAULT_PAGE;
|
||||
}
|
||||
Specification<AssignedApplicationsEntity> spec = searchByPagination( assignedApplicationPageableRequestBean, user,userId);
|
||||
Page<AssignedApplicationsEntity> entityPage = assignedApplicationsRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
|
||||
Specification<AssignedApplicationsView> spec = searchByPagination( assignedApplicationPageableRequestBean, user,userId);
|
||||
Page<AssignedApplicationsView> entityPage = assignedApplicationsViewRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
|
||||
// Prepare the response
|
||||
|
||||
|
||||
List<AssignedApplicationsResponse> assignedApplicationsResponses = entityPage.getContent().stream()
|
||||
.map(application -> {
|
||||
AssignedApplicationsResponse response = convertEntityToResponse(application);
|
||||
return response;
|
||||
})
|
||||
List<AssignedApplicationViewResponse> assignedApplicationsResponses = entityPage.getContent().stream()
|
||||
.map(this::getAssignedApplicationResponseByView)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
|
||||
|
||||
PageableResponseBean<List<AssignedApplicationsResponse>> pageableResponseBean = new PageableResponseBean<>();
|
||||
PageableResponseBean<List<AssignedApplicationViewResponse>> pageableResponseBean = new PageableResponseBean<>();
|
||||
pageableResponseBean.setBody(assignedApplicationsResponses);
|
||||
pageableResponseBean.setCurrentPage(entityPage.getNumber() + 1);
|
||||
pageableResponseBean.setTotalPages(entityPage.getTotalPages());
|
||||
@@ -334,7 +333,7 @@ public class AssignedApplicationsDao {
|
||||
return pageableResponseBean;
|
||||
}
|
||||
|
||||
public Specification<AssignedApplicationsEntity> searchByPagination(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean, UserEntity userEntity,Long userId) {
|
||||
public Specification<AssignedApplicationsView> searchByPagination(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean, UserEntity userEntity,Long userId) {
|
||||
return (root, query, criteriaBuilder) -> {
|
||||
|
||||
List<Predicate> predicates = getPredicates(assignedApplicationPageableRequestBean, criteriaBuilder, root, userEntity,userId);
|
||||
@@ -350,30 +349,35 @@ public class AssignedApplicationsDao {
|
||||
sortBy.setSortDesc(assignedApplicationPageableRequestBean.getGlobalFilters().getSortBy().getSortDesc());
|
||||
}
|
||||
}
|
||||
Path<?> sortPath;
|
||||
Join<AssignedApplicationsEntity, ApplicationEntity> applicationJoin = root.join(GepafinConstant.APPLICATION, JoinType.LEFT);
|
||||
// Path<?> sortPath;
|
||||
// Join<AssignedApplicationsEntity, ApplicationEntity> applicationJoin = root.join(GepafinConstant.APPLICATION, JoinType.LEFT);
|
||||
//
|
||||
// if (GepafinConstant.APPLICATION_ID.equals(sortBy.getColumnName())) {
|
||||
// sortPath = root.join(GepafinConstant.APPLICATION, JoinType.LEFT).get(GepafinConstant.ID); // Join ApplicationEntity and sort by application.id
|
||||
// }
|
||||
// else if (GepafinConstant.PROTOCOL_NUMBER.equals(sortBy.getColumnName())) {
|
||||
// Join<ApplicationEntity, ProtocolEntity> protocolJoin = applicationJoin.join(GepafinConstant.PROTOCOL, JoinType.LEFT);
|
||||
// sortPath = protocolJoin.get(GepafinConstant.PROTOCOL_NUMBER);
|
||||
// }
|
||||
// else {
|
||||
// sortPath = root.get(sortBy.getColumnName()); // Sorting by a field in AmendmentEntity
|
||||
// }
|
||||
// query.orderBy(criteriaBuilder.desc(sortPath));
|
||||
// if (Boolean.FALSE.equals(sortBy.getSortDesc())) {
|
||||
// query.orderBy(criteriaBuilder.asc(sortPath));
|
||||
// }
|
||||
// return query.where(criteriaBuilder.and(predicates.toArray(new Predicate[0]))).getRestriction();
|
||||
|
||||
Path<?> sortPath = root.get(sortBy.getColumnName()); // All fields are accessible directly in the view
|
||||
query.orderBy(sortBy.getSortDesc() ? criteriaBuilder.desc(sortPath) : criteriaBuilder.asc(sortPath));
|
||||
|
||||
if (GepafinConstant.APPLICATION_ID.equals(sortBy.getColumnName())) {
|
||||
sortPath = root.join(GepafinConstant.APPLICATION, JoinType.LEFT).get(GepafinConstant.ID); // Join ApplicationEntity and sort by application.id
|
||||
}
|
||||
else if (GepafinConstant.PROTOCOL_NUMBER.equals(sortBy.getColumnName())) {
|
||||
Join<ApplicationEntity, ProtocolEntity> protocolJoin = applicationJoin.join(GepafinConstant.PROTOCOL, JoinType.LEFT);
|
||||
sortPath = protocolJoin.get(GepafinConstant.PROTOCOL_NUMBER);
|
||||
}
|
||||
else {
|
||||
sortPath = root.get(sortBy.getColumnName()); // Sorting by a field in AmendmentEntity
|
||||
}
|
||||
query.orderBy(criteriaBuilder.desc(sortPath));
|
||||
if (Boolean.FALSE.equals(sortBy.getSortDesc())) {
|
||||
query.orderBy(criteriaBuilder.asc(sortPath));
|
||||
}
|
||||
return query.where(criteriaBuilder.and(predicates.toArray(new Predicate[0]))).getRestriction();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private List<Predicate> getPredicates(AssignedApplicationPageableRequestBean assignedApplicationPageableRequestBean,
|
||||
CriteriaBuilder criteriaBuilder, Root<AssignedApplicationsEntity> root, UserEntity userEntity,Long userId) {
|
||||
CriteriaBuilder criteriaBuilder, Root<AssignedApplicationsView> root, UserEntity userEntity,Long userId) {
|
||||
|
||||
Integer year = null;
|
||||
String search = null;
|
||||
@@ -404,12 +408,35 @@ public class AssignedApplicationsDao {
|
||||
|
||||
}
|
||||
// Search in `title` and `message` (if search term is provided)
|
||||
if (search != null && !search.isEmpty()) {
|
||||
Predicate titlePredicate = criteriaBuilder.like(
|
||||
criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
|
||||
"%" + search.toUpperCase() + "%"
|
||||
);
|
||||
predicates.add(criteriaBuilder.or(titlePredicate));
|
||||
// if (search != null && !search.isEmpty()) {
|
||||
// Predicate titlePredicate = criteriaBuilder.like(
|
||||
// criteriaBuilder.upper(root.get(GepafinConstant.NOTE)),
|
||||
// "%" + search.toUpperCase() + "%"
|
||||
// );
|
||||
// predicates.add(criteriaBuilder.or(titlePredicate));
|
||||
// }
|
||||
|
||||
if (search != null && !search.trim().isEmpty()) {
|
||||
String pattern = "%" + search.toUpperCase() + "%";
|
||||
List<Predicate> searchPredicates = new ArrayList<>();
|
||||
|
||||
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.CALL_NAME)), pattern));
|
||||
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.COMPANY_NAME)), pattern));
|
||||
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.STATUS)), pattern));
|
||||
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.NDG_STRING)), pattern));
|
||||
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.APPOINTMENT_ID)), pattern));
|
||||
searchPredicates.add(criteriaBuilder.like(criteriaBuilder.upper(root.get(GepafinConstant.APPLICATION_STATUS)), pattern));
|
||||
|
||||
// Convert numeric fields to string for search (optional and DB-specific; otherwise exact match)
|
||||
try {
|
||||
Long searchLong = Long.parseLong(search);
|
||||
searchPredicates.add(criteriaBuilder.equal(root.get(GepafinConstant.APPLICATION_ID), searchLong));
|
||||
searchPredicates.add(criteriaBuilder.equal(root.get(GepafinConstant.PROTOCOL_NUMBER), searchLong));
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Ignore if search is not a number
|
||||
}
|
||||
|
||||
predicates.add(criteriaBuilder.or(searchPredicates.toArray(new Predicate[0])));
|
||||
}
|
||||
|
||||
// Filter by `status` (if status list is provided)
|
||||
@@ -421,12 +448,31 @@ public class AssignedApplicationsDao {
|
||||
}
|
||||
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
|
||||
|
||||
applyFilters(root, criteriaBuilder, predicates, filters);
|
||||
|
||||
Utils.applyFiltersByPagination(root, criteriaBuilder, predicates, filters);
|
||||
|
||||
return predicates;
|
||||
|
||||
}
|
||||
|
||||
private AssignedApplicationViewResponse getAssignedApplicationResponseByView(AssignedApplicationsView view) {
|
||||
AssignedApplicationViewResponse response = new AssignedApplicationViewResponse();
|
||||
response.setId(view.getId());
|
||||
response.setUserId(view.getUserId());
|
||||
response.setStatus(AssignedApplicationEnum.valueOf(view.getStatus()));
|
||||
response.setApplicationId(view.getApplicationId());
|
||||
response.setApplicationStatus(ApplicationStatusTypeEnum.valueOf(view.getApplicationStatus()));
|
||||
response.setSubmissionDate(view.getSubmissionDate());
|
||||
response.setEvaluationEndDate(view.getEvaluationEndDate());
|
||||
response.setNdg(view.getNdg());
|
||||
response.setAppointmentId(view.getAppointmentId());
|
||||
response.setProtocolNumber(view.getProtocolNumber());
|
||||
response.setCallName(view.getCallName());
|
||||
response.setCompanyName(view.getCompanyName());
|
||||
response.setCreatedDate(view.getCreatedDate());
|
||||
response.setUpdatedDate(view.getUpdatedDate());
|
||||
return response;
|
||||
}
|
||||
|
||||
public AssignedApplicationsResponse updateAssignedApplicationStatus(HttpServletRequest request, Long assignedApplicationId, AssignedApplicationEnum status) {
|
||||
|
||||
AssignedApplicationsEntity assignedApplication = validateAssignedApplication(assignedApplicationId);
|
||||
|
||||
@@ -124,6 +124,9 @@ public class CallDao {
|
||||
@Autowired
|
||||
private EvaluationFormDao evalualtionFormDao;
|
||||
|
||||
@Autowired
|
||||
private ApplicationRepository applicationRepository;
|
||||
|
||||
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
|
||||
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
|
||||
CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
|
||||
@@ -598,8 +601,8 @@ public class CallDao {
|
||||
if (!requestEndDate.equals(storedEndDate)) { // Check if dates are different
|
||||
|
||||
setIfUpdated(callEntity::getEndDate, callEntity::setEndDate, dates.get(1));
|
||||
callEntity.setStatus(CallStatusEnum.PUBLISH.getValue());
|
||||
callRepository.save(callEntity);
|
||||
// callEntity.setStatus(CallStatusEnum.PUBLISH.getValue());
|
||||
// callRepository.save(callEntity);
|
||||
isEndDateUpdated = true;
|
||||
}
|
||||
}
|
||||
@@ -611,13 +614,13 @@ public class CallDao {
|
||||
|
||||
if (!requestEndTime.equals(storedEndTime)) {
|
||||
setIfUpdated(callEntity::getEndTime, callEntity::setEndTime, DateTimeUtil.parseTime(updateCallRequest.getEndTime()));
|
||||
callEntity.setStatus(CallStatusEnum.PUBLISH.getValue());
|
||||
callRepository.save(callEntity);
|
||||
// callEntity.setStatus(CallStatusEnum.PUBLISH.getValue());
|
||||
// callRepository.save(callEntity);
|
||||
isEndTimeUpdated = true;
|
||||
}
|
||||
}
|
||||
if (isEndDateUpdated || isEndTimeUpdated) {
|
||||
|
||||
callRepository.save(callEntity);
|
||||
loggingUtil.logUserAction(UserActionRequest.builder()
|
||||
.request(request)
|
||||
.actionType(UserActionLogsEnum.UPDATE)
|
||||
@@ -796,6 +799,7 @@ public class CallDao {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.COMPANY_ID_REQUIRED_FOR_PREFERRED_CALL));
|
||||
}
|
||||
expirePublishedCalls(request);
|
||||
Specification<CallEntity> spec = buildCallSpecification(request, user, companyId, onlyPreferredCall, onlyConfidiCall, callStatusList);
|
||||
|
||||
List<CallEntity> calls = callRepository.findAll(spec);
|
||||
@@ -901,7 +905,7 @@ public class CallDao {
|
||||
public CallResponse updateCallStatus(CallEntity callEntity, CallStatusEnum statusReq) {
|
||||
CallEntity oldCallEntity = Utils.getClonedEntityForData(callEntity);
|
||||
CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus());
|
||||
validateStatusChange(currentStatus, statusReq);
|
||||
validateStatusChange(currentStatus, statusReq, callEntity.getId());
|
||||
callEntity.setStatus(statusReq.getValue());
|
||||
callEntity = callRepository.save(callEntity);
|
||||
|
||||
@@ -921,36 +925,37 @@ public class CallDao {
|
||||
return convertToCallResponseBean(callEntity);
|
||||
}
|
||||
|
||||
private void validateStatusChange(CallStatusEnum currentStatus, CallStatusEnum newStatus) {
|
||||
private void validateStatusChange(CallStatusEnum currentStatus, CallStatusEnum newStatus, Long callId) {
|
||||
|
||||
if (currentStatus == newStatus) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.STATUS_SAME_ERROR));
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.STATUS_SAME_ERROR));
|
||||
}
|
||||
|
||||
switch (currentStatus) {
|
||||
case DRAFT:
|
||||
if (newStatus == CallStatusEnum.READY_TO_PUBLISH || newStatus == CallStatusEnum.PUBLISH) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_DRAFT));
|
||||
}
|
||||
break;
|
||||
case PUBLISH:
|
||||
if (newStatus == CallStatusEnum.READY_TO_PUBLISH || newStatus == CallStatusEnum.DRAFT) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_PUBLISH));
|
||||
}
|
||||
break;
|
||||
case DRAFT:
|
||||
if (newStatus == CallStatusEnum.READY_TO_PUBLISH || newStatus == CallStatusEnum.PUBLISH) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_DRAFT));
|
||||
}
|
||||
break;
|
||||
|
||||
case EXPIRED:
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.STATUS_CANNOT_BE_CHANGED));
|
||||
case READY_TO_PUBLISH:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
case PUBLISH:
|
||||
if (newStatus == CallStatusEnum.READY_TO_PUBLISH) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_PUBLISH));
|
||||
}
|
||||
if (newStatus == CallStatusEnum.DRAFT && Boolean.TRUE.equals(applicationRepository.existsByCallId(callId))) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.INVALID_STATUS_CHANGE_FROM_PUBLISH_TO_DRAFT));
|
||||
}
|
||||
break;
|
||||
|
||||
case EXPIRED:
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.STATUS_CANNOT_BE_CHANGED));
|
||||
|
||||
case READY_TO_PUBLISH:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public CallEntity validatePublishedCall(Long callId, Long hubId) {
|
||||
CallEntity callEntity= callRepository
|
||||
.findByIdAndStatusAndHubId(callId, CallStatusEnum.PUBLISH.getValue(), hubId);
|
||||
@@ -959,7 +964,7 @@ public class CallDao {
|
||||
Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.CALL_NOT_PUBLISHED));
|
||||
}
|
||||
LocalDate currentDate = DateTimeUtil.LocalDateServerToEurope(LocalDate.now());
|
||||
LocalDate currentDate = DateTimeUtil.DateServerToUTC(LocalDateTime.now()).toLocalDate();
|
||||
LocalTime currentTime = DateTimeUtil.LocalTimeServerToEurope(LocalTime.now());
|
||||
|
||||
if (currentDate.isBefore(callEntity.getStartDate().toLocalDate()) ||
|
||||
@@ -1000,6 +1005,7 @@ public class CallDao {
|
||||
Translator.toLocale(GepafinConstant.COMPANY_ID_REQUIRED_FOR_PREFERRED_CALL)
|
||||
);
|
||||
}
|
||||
expirePublishedCalls(request);
|
||||
Specification<CallEntity> spec = search(request,user, callPageableRequestBean);
|
||||
Page<CallEntity> entityPage;
|
||||
if (Boolean.TRUE.equals(onlyPreferredCall)) {
|
||||
@@ -1078,7 +1084,6 @@ public class CallDao {
|
||||
|
||||
private List<Predicate> getPredicates(HttpServletRequest request,CallPageableRequestBean callPageableRequestBean,
|
||||
CriteriaBuilder criteriaBuilder, Root<CallEntity> root, UserEntity userEntity) {
|
||||
expirePublishedCalls(request);
|
||||
Integer year = null;
|
||||
String search = null;
|
||||
Map<String, FilterCriteria> filters = new HashMap<>();
|
||||
@@ -1162,42 +1167,24 @@ public class CallDao {
|
||||
}
|
||||
|
||||
public void expirePublishedCalls(HttpServletRequest request) {
|
||||
List<CallEntity> expiredCalls = callRepository.findAll((root, query, criteriaBuilder) -> {
|
||||
Predicate isPublished = criteriaBuilder.equal(root.get(GepafinConstant.STATUS), CallStatusEnum.PUBLISH.name());
|
||||
|
||||
// Concatenate date and time as a single string
|
||||
Expression<String> dateTimeString = criteriaBuilder.concat(
|
||||
root.get(GepafinConstant.END_DATE),
|
||||
criteriaBuilder.literal(" ") // Space between date and time
|
||||
);
|
||||
Expression<String> fullDateTimeString = criteriaBuilder.concat(dateTimeString, root.get(GepafinConstant.END_TIME));
|
||||
|
||||
// Convert the concatenated string into TIMESTAMP
|
||||
Expression<LocalDateTime> endDateTime = criteriaBuilder.function(
|
||||
"to_timestamp",
|
||||
LocalDateTime.class,
|
||||
fullDateTimeString,
|
||||
criteriaBuilder.literal("YYYY-MM-DD HH24:MI:SS")
|
||||
);
|
||||
|
||||
Predicate isExpired = criteriaBuilder.lessThan(endDateTime, LocalDateTime.now());
|
||||
|
||||
return criteriaBuilder.and(isPublished, isExpired);
|
||||
});
|
||||
|
||||
if (!expiredCalls.isEmpty()) {
|
||||
for (CallEntity call : expiredCalls) {
|
||||
|
||||
|
||||
LocalDate currentDate = DateTimeUtil.DateServerToUTC(LocalDateTime.now()).toLocalDate();
|
||||
LocalTime currentTime = DateTimeUtil.LocalTimeServerToEurope(LocalTime.now());
|
||||
|
||||
List<CallEntity> expirdedCallList = callRepository.findExpiredCallsWhichIsPublished(CallStatusEnum.PUBLISH.getValue(), currentDate, currentTime);
|
||||
|
||||
if (!expirdedCallList.isEmpty()) {
|
||||
|
||||
loggingUtil.logUserAction(UserActionRequest.builder()
|
||||
.request(request)
|
||||
.actionType(UserActionLogsEnum.UPDATE)
|
||||
.actionContext(UserActionContextEnum.UPDATE_EXPIRED_CALL)
|
||||
.build());
|
||||
for (CallEntity call : expirdedCallList) {
|
||||
CallEntity oldCallEntity = Utils.getClonedEntityForData(call); // Clone before modification
|
||||
call.setStatus(CallStatusEnum.EXPIRED.getValue());
|
||||
|
||||
if (!oldCallEntity.getStatus().equals(call.getStatus())) {
|
||||
// Log user action
|
||||
loggingUtil.logUserAction(UserActionRequest.builder()
|
||||
.request(request)
|
||||
.actionType(UserActionLogsEnum.UPDATE)
|
||||
.actionContext(UserActionContextEnum.UPDATE_EXPIRED_CALL)
|
||||
.build());
|
||||
|
||||
// Add version history log
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder()
|
||||
.request(request)
|
||||
@@ -1205,9 +1192,8 @@ public class CallDao {
|
||||
.oldData(oldCallEntity)
|
||||
.newData(call)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
callRepository.saveAll(expiredCalls); // Save all modified calls at once
|
||||
callRepository.saveAll(expirdedCallList); // Save all modified calls at once
|
||||
}
|
||||
}
|
||||
private void applyFilters(Root<?> root, CriteriaBuilder criteriaBuilder, List<Predicate> predicates, Map<String, FilterCriteria> filters) {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.data.domain.Pageable; // Correct package
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -20,7 +18,6 @@ import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.FaqRepository;
|
||||
import net.gepafin.tendermanagement.service.feignClient.VatCheckService;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -37,7 +34,6 @@ import net.gepafin.tendermanagement.model.response.CompanyResponse;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
|
||||
import static net.gepafin.tendermanagement.util.Utils.convertObjectToJsonString;
|
||||
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
|
||||
|
||||
@Component
|
||||
@@ -73,10 +69,6 @@ public class CompanyDao {
|
||||
private HttpServletRequest request;
|
||||
|
||||
|
||||
@Autowired
|
||||
private VatCheckService vatCheckService; // Service to call VAT API
|
||||
|
||||
|
||||
private static final String NOT_FOUND_JSON = "{\"data\": \"not found\"}";
|
||||
|
||||
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
|
||||
@@ -146,8 +138,6 @@ public class CompanyDao {
|
||||
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(userWithCompany).build());
|
||||
if (StringUtils.isEmpty(companyEntity.getJson())) {
|
||||
companyEntity.setJson(Utils.convertMapIntoJsonString(companyRequest.getVatCheckResponse()));
|
||||
Map<String, Object> vatCheckResponse = companyRequest.getVatCheckResponse();
|
||||
Map<String, Object> data = (Map<String, Object>) vatCheckResponse.get("data");
|
||||
updateCodiceAtecoFieldWithNewJson(companyEntity);
|
||||
companyEntity = companyRepository.save(companyEntity);
|
||||
|
||||
@@ -178,7 +168,7 @@ public class CompanyDao {
|
||||
entity.setAnnualRevenue(request.getAnnualRevenue());
|
||||
entity.setHub(userEntity.getHub());
|
||||
entity.setJson(Utils.convertMapIntoJsonString(request.getVatCheckResponse()));
|
||||
updateCodiceAtecoFieldWithNewJson(entity);
|
||||
updateCodiceAtecoFieldWithNewJson(entity);
|
||||
|
||||
return entity;
|
||||
}
|
||||
@@ -437,7 +427,6 @@ public class CompanyDao {
|
||||
log.info("Company ID {}: JSON field updated successfully.", company.getId());
|
||||
|
||||
// Extract and set codiceAteco field
|
||||
// updateCodiceAtecoField(company);
|
||||
updateCodiceAtecoFieldWithNewJson(company);
|
||||
|
||||
successfulUpdates++;
|
||||
@@ -472,50 +461,38 @@ public class CompanyDao {
|
||||
private void updateCodiceAtecoField(CompanyEntity company) {
|
||||
Map<String, Object> vatCheckResponse = Utils.convertJsonStringToMap(company.getJson());
|
||||
|
||||
if (vatCheckResponse != null && vatCheckResponse.containsKey("data")) {
|
||||
Object dataObj = vatCheckResponse.get("data");
|
||||
|
||||
if (dataObj instanceof Map) {
|
||||
Map<String, Object> dataMap = (Map<String, Object>) dataObj;
|
||||
log.info("Company ID {}: Available keys inside 'data' -> {}", company.getId(), dataMap.keySet());
|
||||
|
||||
if (dataMap.containsKey("dettaglio")) {
|
||||
Object dettaglioObj = dataMap.get("dettaglio");
|
||||
|
||||
if (dettaglioObj instanceof Map) {
|
||||
Map<String, Object> dettaglio = (Map<String, Object>) dettaglioObj;
|
||||
|
||||
if (dettaglio.containsKey("codice_ateco")) {
|
||||
Object codiceAtecoObj = dettaglio.get("codice_ateco");
|
||||
|
||||
if (codiceAtecoObj instanceof String) {
|
||||
String codiceAteco = (String) codiceAtecoObj;
|
||||
|
||||
if (codiceAteco != null && !codiceAteco.isEmpty()) {
|
||||
company.setCodiceAteco(codiceAteco);
|
||||
log.info("Company ID {}: codiceAteco updated to {}", company.getId(), codiceAteco);
|
||||
} else {
|
||||
log.warn("Company ID {}: codiceAteco is null or empty in the response.", company.getId());
|
||||
}
|
||||
} else {
|
||||
log.warn("Company ID {}: 'codice_ateco' is not a string, actual type: {}", company.getId(), codiceAtecoObj.getClass());
|
||||
}
|
||||
} else {
|
||||
log.warn("Company ID {}: 'dettaglio' does not contain 'codice_ateco' key.", company.getId());
|
||||
}
|
||||
} else {
|
||||
log.warn("Company ID {}: 'dettaglio' is not a Map, actual type: {}", company.getId(), dettaglioObj.getClass());
|
||||
}
|
||||
} else {
|
||||
log.warn("Company ID {}: 'dettaglio' section is missing inside 'data'!", company.getId());
|
||||
}
|
||||
} else {
|
||||
log.warn("Company ID {}: 'data' is not a Map, actual type: {}", company.getId(), dataObj.getClass());
|
||||
}
|
||||
} else {
|
||||
log.warn("Company ID {}: 'data' section missing in the JSON response.", company.getId());
|
||||
if (vatCheckResponse == null) {
|
||||
log.warn("Company ID {}: Invalid JSON response.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
Object dataObj = vatCheckResponse.get("data");
|
||||
if (!(dataObj instanceof Map<?, ?> dataMap)) {
|
||||
log.warn("Company ID {}: 'data' is missing or not a valid object.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!dataMap.containsKey("dettaglio")) {
|
||||
log.warn("Company ID {}: 'dettaglio' not present inside 'data'. Skipping codiceAteco update.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
Object dettaglioObj = dataMap.get("dettaglio");
|
||||
if (!(dettaglioObj instanceof Map<?, ?> dettaglio)) {
|
||||
log.warn("Company ID {}: 'dettaglio' is not a valid object.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
Object codiceAtecoObj = dettaglio.get("codice_ateco");
|
||||
if (!(codiceAtecoObj instanceof String codiceAteco) || codiceAteco.isEmpty()) {
|
||||
log.warn("Company ID {}: 'codice_ateco' is missing, empty, or not a string.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
company.setCodiceAteco(codiceAteco);
|
||||
logCodiceAtecoUpdate(company, codiceAteco);
|
||||
}
|
||||
|
||||
private void updateCodiceAtecoFieldWithNewJson(CompanyEntity company) {
|
||||
if (company == null || company.getJson() == null || company.getJson().isEmpty()) {
|
||||
log.warn("Company is null or JSON data is empty.");
|
||||
@@ -530,32 +507,43 @@ public class CompanyDao {
|
||||
|
||||
// Extract 'data' section
|
||||
Map<String, Object> dataMap = Utils.extractMap(companyDataMap, "data");
|
||||
Object dataObj = companyDataMap.get("data");
|
||||
|
||||
if (dataMap == null) {
|
||||
log.warn("Company ID {}: 'data' section is missing or invalid in the JSON.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract 'atecoClassification' section
|
||||
Map<String, Object> atecoClassificationMap = Utils.extractMap(dataMap, "atecoClassification");
|
||||
if (atecoClassificationMap == null) {
|
||||
log.warn("Company ID {}: 'atecoClassification' section is missing or invalid.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract 'ateco' section
|
||||
Map<String, Object> atecoMap = Utils.extractMap(atecoClassificationMap, "ateco");
|
||||
if (atecoMap == null) {
|
||||
log.warn("Company ID {}: 'ateco' section is missing or invalid.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract and set 'code'
|
||||
String atecoCode = Utils.extractString(atecoMap, "code");
|
||||
if (atecoCode != null && !atecoCode.isEmpty()) {
|
||||
company.setCodiceAteco(atecoCode);
|
||||
log.info("Company ID {}: codiceAteco updated to {}", company.getId(), atecoCode);
|
||||
if (dataObj instanceof Map<?, ?>) {
|
||||
// if data is a single object
|
||||
updateCodiceAtecoField(company);
|
||||
} else {
|
||||
log.warn("Company ID {}: 'code' inside 'ateco' is empty or missing.", company.getId());
|
||||
// Extract 'atecoClassification' section
|
||||
Map<String, Object> atecoClassificationMap = Utils.extractMap(dataMap, "atecoClassification");
|
||||
if (atecoClassificationMap == null) {
|
||||
log.warn("Company ID {}: 'atecoClassification' section is missing or invalid.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract 'ateco' section
|
||||
Map<String, Object> atecoMap = Utils.extractMap(atecoClassificationMap, "ateco");
|
||||
if (atecoMap == null) {
|
||||
log.warn("Company ID {}: 'ateco' section is missing or invalid.", company.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract and set 'code'
|
||||
String atecoCode = Utils.extractString(atecoMap, "code");
|
||||
if (atecoCode != null && !atecoCode.isEmpty()) {
|
||||
company.setCodiceAteco(atecoCode);
|
||||
logCodiceAtecoUpdate(company, atecoCode);
|
||||
} else {
|
||||
log.warn("Company ID {}: 'code' inside 'ateco' is empty or missing.", company.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void logCodiceAtecoUpdate(CompanyEntity company, String atecoCode) {
|
||||
|
||||
log.info("Company ID {}: codiceAteco updated to {}", company.getId(), atecoCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,7 +209,6 @@ public class DelegationDao {
|
||||
|
||||
companyDao.validateCompany(companyId);
|
||||
companyDao.getUserWithCompany(userEntity.getId(), companyId);
|
||||
validateFileType(file);
|
||||
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyId);
|
||||
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
|
||||
.findByUserIdAndUserWithCompanyIdAndStatus(userEntity.getId(), userWithCompanyEntity.getId(),
|
||||
|
||||
@@ -511,7 +511,7 @@ public class FormDao {
|
||||
// Map<String, Object> customData=null;
|
||||
try {
|
||||
// Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
|
||||
vatCheckDao.checkVatNumberApi(value);
|
||||
vatCheckDao.checkVatNumber(value);
|
||||
// if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
|
||||
// customData = vatCheckResponse;
|
||||
// }
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import feign.FeignException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
import net.gepafin.tendermanagement.enums.VatCheckVersionTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.response.VatCheckResponseBean;
|
||||
import net.gepafin.tendermanagement.service.feignClient.VatCheckService;
|
||||
import net.gepafin.tendermanagement.util.LoggingUtil;
|
||||
import net.gepafin.tendermanagement.repositories.GlobalConfigRepository;
|
||||
import net.gepafin.tendermanagement.service.feignClient.VatCheckV1Service;
|
||||
import net.gepafin.tendermanagement.service.feignClient.VatCheckV2Service;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -20,8 +21,8 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -30,104 +31,103 @@ import java.util.Map;
|
||||
public class VatCheckDao {
|
||||
|
||||
@Autowired
|
||||
private VatCheckService vatCheckService;
|
||||
private VatCheckV2Service vatCheckV2Service;
|
||||
|
||||
@Value("${vatCheckNewToken}")
|
||||
public String vatCheckNewToken;
|
||||
@Autowired
|
||||
private VatCheckV1Service vatCheckV1Service;
|
||||
|
||||
@Value("${vatCheckTokenV2}")
|
||||
public String vatCheckTokenV2;
|
||||
|
||||
@Value("${vatCheckTokenV1}")
|
||||
public String vatCheckTokenV1;
|
||||
|
||||
@Value("${isVatCheckGloballyDisabled}")
|
||||
public String isVatCheckGloballyDisabled;
|
||||
|
||||
@Autowired
|
||||
private GlobalConfigRepository globalConfigRepository;
|
||||
|
||||
public final Logger log = LoggerFactory.getLogger(VatCheckDao.class);
|
||||
|
||||
@Autowired
|
||||
private LoggingUtil loggingUtil;
|
||||
public VatCheckResponseBean checkVatNumberV1(String vatNumber) {
|
||||
VatCheckResponseBean vatCheckResponseBean = new VatCheckResponseBean();
|
||||
vatCheckResponseBean.setValid(false);
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
if (Boolean.TRUE.equals(Boolean.parseBoolean(isVatCheckGloballyDisabled))) {
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
return vatCheckResponseBean;
|
||||
}
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set(GepafinConstant.AUTHORIZATION, "Bearer " + vatCheckTokenV1);
|
||||
headers.add(org.apache.http.HttpHeaders.USER_AGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0");
|
||||
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
URI baseUrl = URI.create(GepafinConstant.CHECK_VATNUMBER_URL_V1);
|
||||
ResponseEntity<Map<String, Object>> response = vatCheckV1Service.checkVatNumber(baseUrl, vatNumber, headers);
|
||||
|
||||
// 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))) {
|
||||
// vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
// return vatCheckResponseBean;
|
||||
// }
|
||||
// Map<String, Object> responseBody = new HashMap<>();
|
||||
// try {
|
||||
// HttpHeaders headers = new HttpHeaders();
|
||||
// headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||
// headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
// headers.set(GepafinConstant.AUTHORIZATION, "Bearer " + vatCheckNewToken);
|
||||
// headers.add(org.apache.http.HttpHeaders.USER_AGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0");
|
||||
//
|
||||
// URI baseUrl = URI.create(GepafinConstant.CHECK_VATNUMBER_V2_NEW_URL);
|
||||
// ResponseEntity<Map<String, Object>> response = vatCheckService.checkVatNumber(baseUrl, vatNumber, headers);
|
||||
//
|
||||
//
|
||||
// if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
|
||||
// log.info("Successfully checked vat number");
|
||||
// Map<String, Object> responseMap = response.getBody();
|
||||
// processValidResponse(responseMap, vatCheckResponseBean);
|
||||
// }
|
||||
// } catch (FeignException 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));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public VatCheckResponseBean checkVatNumber(String vatNumber) {
|
||||
// try {
|
||||
// return checkVatNumberApi(vatNumber);
|
||||
// } catch (Exception e) {
|
||||
// log.error("Error in checkVatNumber: {}", e.getMessage());
|
||||
// VatCheckResponseBean vatCheckResponseBean = new VatCheckResponseBean();
|
||||
// vatCheckResponseBean.setValid(false);
|
||||
// vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
// return vatCheckResponseBean;
|
||||
// }
|
||||
// }
|
||||
if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
|
||||
logSuccess();
|
||||
Map<String, Object> responseMap = response.getBody();
|
||||
if (responseMap != null) {
|
||||
processValidResponseV1(responseMap, vatCheckResponseBean);
|
||||
} else {
|
||||
log.warn("Response map or vatCheckResponseBean is null.");
|
||||
}
|
||||
}
|
||||
|
||||
} catch (FeignException ex) {
|
||||
if (ex.status() == 406) {
|
||||
try {
|
||||
Map<String, Object> errorResponse = Utils.parseErrorResponse(ex.contentUTF8());
|
||||
processValidResponseV1(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 processValidResponseV1(Map<String, Object> responseMap, VatCheckResponseBean vatCheckResponseBean) {
|
||||
Object dataObj = responseMap.get("data");
|
||||
if (dataObj instanceof Map<?, ?> rawDataMap) {
|
||||
Map<String, Object> responseBody = new LinkedHashMap<>();
|
||||
rawDataMap.forEach((k, v) -> {
|
||||
if (k instanceof String strKey) {
|
||||
responseBody.put(strKey, v);
|
||||
}
|
||||
});
|
||||
|
||||
List.of("timestamp_creation", "timestamp_last_update", "id", "data_iscrizione").forEach(responseBody.keySet()::remove);
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public VatCheckResponseBean checkVatNumber(String vatNumber) {
|
||||
|
||||
try {
|
||||
return checkVatNumberApi(vatNumber);
|
||||
String vatApiVersion = getVatCheckVersion();
|
||||
if(!isVatCheckApiV2(vatApiVersion)){
|
||||
return checkVatNumberV1(vatNumber);
|
||||
}
|
||||
return checkVatNumberV2(vatNumber);
|
||||
} catch (Exception e) {
|
||||
log.error("Error in checkVatNumber: {}", e.getMessage());
|
||||
logErrorMessage(e);
|
||||
VatCheckResponseBean vatCheckResponseBean = new VatCheckResponseBean();
|
||||
vatCheckResponseBean.setValid(false);
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
@@ -135,7 +135,7 @@ public class VatCheckDao {
|
||||
}
|
||||
}
|
||||
|
||||
public VatCheckResponseBean checkVatNumberApi(String vatNumber) {
|
||||
public VatCheckResponseBean checkVatNumberV2(String vatNumber) {
|
||||
|
||||
VatCheckResponseBean vatCheckResponseBean = new VatCheckResponseBean();
|
||||
vatCheckResponseBean.setValid(false);
|
||||
@@ -147,13 +147,13 @@ public class VatCheckDao {
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||
headers.set(GepafinConstant.AUTHORIZATION, "Bearer " + vatCheckNewToken);
|
||||
headers.set(GepafinConstant.AUTHORIZATION, "Bearer " + vatCheckTokenV2);
|
||||
|
||||
URI baseUrl = URI.create(GepafinConstant.CHECK_VATNUMBER_V2_NEW_URL_IT_ADVANCE);
|
||||
ResponseEntity<Map<String, Object>> response = vatCheckService.checkVatNumber(baseUrl, vatNumber, headers);
|
||||
URI baseUrl = URI.create(GepafinConstant.CHECK_VATNUMBER_URL_V2);
|
||||
ResponseEntity<Map<String, Object>> response = vatCheckV2Service.checkVatNumber(baseUrl, vatNumber, headers);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
|
||||
log.info("Successfully checked vat number");
|
||||
logSuccess();
|
||||
Map<String, Object> responseMap = response.getBody();
|
||||
processValidResponse(responseMap, vatCheckResponseBean);
|
||||
}
|
||||
@@ -172,33 +172,65 @@ public class VatCheckDao {
|
||||
}
|
||||
return vatCheckResponseBean;
|
||||
}
|
||||
|
||||
public static void processValidResponse(Map<String, Object> responseMap, VatCheckResponseBean vatCheckResponseBean) {
|
||||
|
||||
if (responseMap != null && responseMap.containsKey("data")) {
|
||||
Object dataObject = responseMap.get("data");
|
||||
|
||||
if (dataObject instanceof List && !((List<?>) dataObject).isEmpty()) {
|
||||
dataObject = ((List<?>) dataObject).get(0);
|
||||
}
|
||||
|
||||
if (dataObject instanceof Map) {
|
||||
Map<String, Object> responseBody = (Map<String, Object>) dataObject;
|
||||
|
||||
responseBody.remove("creationTimestamp");
|
||||
responseBody.remove("lastUpdateTimestamp");
|
||||
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 {
|
||||
if (responseMap == null || !responseMap.containsKey("data")) {
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
return;
|
||||
}
|
||||
|
||||
Object dataObject = responseMap.get("data");
|
||||
if (!(dataObject instanceof List<?> dataList) || dataList.isEmpty()) {
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
return;
|
||||
}
|
||||
|
||||
List<Map<String, Object>> processedList = new ArrayList<>();
|
||||
|
||||
for (Object item : dataList) {
|
||||
if (item instanceof Map<?, ?> mapItem) {
|
||||
Map<String, Object> responseBody = new LinkedHashMap<>();
|
||||
mapItem.forEach((key, value) -> {
|
||||
if (key instanceof String strKey) {
|
||||
responseBody.put(strKey, value);
|
||||
}
|
||||
});
|
||||
|
||||
List.of("creationTimestamp", "lastUpdateTimestamp", "id").forEach(responseBody.keySet()::remove);
|
||||
|
||||
processedList.add(responseBody);
|
||||
}
|
||||
}
|
||||
|
||||
if (processedList.isEmpty()) {
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
|
||||
return;
|
||||
}
|
||||
|
||||
vatCheckResponseBean.setValid(true);
|
||||
vatCheckResponseBean.setMessage(Translator.toLocale(GepafinConstant.VALID_VATNUMBER_MSG));
|
||||
vatCheckResponseBean.setVatCheckResponse(Map.of("data", processedList));
|
||||
}
|
||||
|
||||
private void logSuccess() {
|
||||
|
||||
log.info("Successfully checked vat number");
|
||||
}
|
||||
|
||||
private static boolean isVatCheckApiV2(String vatApiVersion) {
|
||||
boolean isNotBlank = StringUtils.isNotBlank(vatApiVersion);
|
||||
boolean isNotEmpty = StringUtils.isNotEmpty(vatApiVersion);
|
||||
return isNotBlank && isNotEmpty && Boolean.TRUE.equals(vatApiVersion.equals(VatCheckVersionTypeEnum.V2.getValue()));
|
||||
}
|
||||
|
||||
private String getVatCheckVersion() {
|
||||
|
||||
return globalConfigRepository.findContentByTypeAndIsDeletedFalse(GepafinConstant.VAT_CHECK_API_VERSION);
|
||||
}
|
||||
|
||||
private void logErrorMessage(Exception e) {
|
||||
|
||||
log.error("Error in checkVatNumber: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user