Merge branch 'develop' of https://github.com/Kitzanos/GEPAFIN-BE into feature/GEPAFINBE-199
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user