Resolved conflicts

This commit is contained in:
nisha
2025-02-17 16:37:34 +05:30
112 changed files with 3861 additions and 293 deletions

View File

@@ -31,6 +31,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundExceptio
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.h2.util.IOUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -49,11 +50,16 @@ import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -94,29 +100,29 @@ public class ApplicationDao {
@Autowired
private FlowDataRepository flowDataRepository;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
@Autowired
private Validator validator;
@Autowired
private CompanyService companyService;
@Autowired
private S3PathConfig s3PathConfig;
@Autowired
private SystemEmailTemplatesService systemEmailTemplatesService;
@Autowired
private AssignedApplicationsRepository assignedApplicationsRepository;
@Value("${default_System_Receiver_Email}")
private String defaultSystemReceiverEmail;
@Value("${rinaldo_email}")
private String rinaldoEmail;
@Value("${carlo_email}")
private String carloEmail;
@@ -125,37 +131,37 @@ public class ApplicationDao {
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
// @Value("${aws.s3.url.folder.signed.document}")
// private String signedDocumentS3Folder;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
@Autowired
private UserService userService;
@Autowired
private S3PathConfig s3ConfigBean;
@Autowired
private ProtocolDao protocolDao;
@Autowired
private HubService hubService;
@Autowired
private EmailNotificationDao emailNotificationDao;
@Autowired
private FormDao formDao;
@Autowired
private EmailLogDao emailLogDao;
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
@@ -183,6 +189,7 @@ public class ApplicationDao {
@Autowired
private ApplicationEvaluationRepository applicationEvaluationRepository;
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId);
// callService.validatePublishedCall(formEntity.getCall().getId());
@@ -234,6 +241,7 @@ public class ApplicationDao {
entity.setUserWithCompany(userWithCompany);
entity.setIsDeleted(false);
entity.setStatus(ApplicationStatusTypeEnum.DRAFT.getValue());
entity.setEvaluationVersion(call.getEvaluationVersion());
return entity;
}
@@ -257,7 +265,7 @@ public class ApplicationDao {
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(
// applicationFormEntity.getForm().getContent(), ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(applicationFormEntity.getForm()).getContent();
for (ApplicationFormFieldEntity applicationFormFieldEntity : applicationFormFieldEntities) {
@@ -308,7 +316,7 @@ public class ApplicationDao {
);
}
ApplicationEntity oldApplicationDataEntity = Utils.getClonedEntityForData(applicationEntity);
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
applicationEntity.setIsDeleted(true);
applicationEntity = applicationRepository.save(applicationEntity);
@@ -355,9 +363,9 @@ public class ApplicationDao {
//
// return applicationResponses;
// }
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId,List<ApplicationStatusTypeEnum> statusList) {
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
Specification<ApplicationEntity> spec = search(userEntity, callId, companyId,statusList);
@@ -402,7 +410,7 @@ public class ApplicationDao {
ApplicationResponse responseBean = new ApplicationResponse();
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalFormSteps = flowFormDao.calculateTotalSteps(flowEdgesList);
Long completedSteps= Long.valueOf(flowFormDao.getCompletedSteps(applicationEntity));
Long completedSteps= Long.valueOf(flowFormDao.getCompletedSteps(applicationEntity, false));
Integer progress = calculateProgress(totalFormSteps, completedSteps);
responseBean.setId(applicationEntity.getId());
responseBean.setProgress(progress);
@@ -413,6 +421,7 @@ public class ApplicationDao {
responseBean.setCallId(applicationEntity.getCall().getId());
responseBean.setSubmissionDate(applicationEntity.getSubmissionDate());
responseBean.setStatus(applicationEntity.getStatus());
responseBean.setEvaluationVersion(EvaluationVersionEnum.valueOf(applicationEntity.getCall().getEvaluationVersion()));
responseBean.setComments(applicationEntity.getComments());
responseBean.setCompanyId(applicationEntity.getCompanyId());
Optional<AssignedApplicationsEntity> assignedApplicationsOptional =
@@ -480,15 +489,18 @@ public class ApplicationDao {
public List<ApplicationFormFieldEntity> createOrUpdateMultipleFormFields(List<ApplicationFormFieldRequestBean> formFieldResponseBeans,
ApplicationFormEntity applicationFormEntity, FormEntity formEntity) {
FieldValidator fieldValidator = FieldValidator.create();
List<ApplicationFormFieldEntity> existingFields = applicationFormFieldRepository.findByApplicationFormId(applicationFormEntity.getId());
return formFieldResponseBeans.stream().map(requestBean -> createOrUpdateApplicationFormField(requestBean, applicationFormEntity, existingFields, formEntity))
List<ApplicationFormFieldEntity> applicationFormFieldEntities=formFieldResponseBeans.stream().map(requestBean -> createOrUpdateApplicationFormField(requestBean, applicationFormEntity, existingFields, formEntity,fieldValidator))
.collect(Collectors.toList());
fieldValidator.validate();
return applicationFormFieldEntities;
}
public ApplicationFormFieldEntity createOrUpdateApplicationFormField(ApplicationFormFieldRequestBean applicationFormFieldRequestBean,
ApplicationFormEntity applicationFormEntity, List<ApplicationFormFieldEntity> applicationFormFieldEntities, FormEntity formEntity) {
ApplicationFormEntity applicationFormEntity, List<ApplicationFormFieldEntity> applicationFormFieldEntities, FormEntity formEntity,FieldValidator fieldValidator) {
ApplicationFormFieldEntity applicationFormFieldEntity = new ApplicationFormFieldEntity();
@@ -497,27 +509,23 @@ public class ApplicationDao {
VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT;
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
contentResponseBeans.stream()
.filter(content -> "numberinput".equals(content.getName()))
.map(ContentResponseBean::getSettings)
.flatMap(List::stream)
.filter(setting -> "isRequestedAmount".equals(setting.getName()) && Boolean.TRUE.equals(setting.getValue()))
.findFirst()
.ifPresent(setting -> {
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
if(fieldValue!=null) {
if (fieldValue instanceof String) {
try {
BigDecimal amountRequested = new BigDecimal((String) fieldValue);
applicationFormEntity.getApplication().setAmountRequested(amountRequested);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Field value is not a valid number: " + fieldValue, e);
}
} else {
throw new IllegalArgumentException("Field value is not a String: " + fieldValue);
}
}
});
contentResponseBeans.stream()
.filter(content -> "numberinput".equals(content.getName()) && content.getId().toString().equals(applicationFormFieldRequestBean.getFieldId()))
.map(ContentResponseBean::getSettings)
.flatMap(List::stream)
.filter(setting -> "isRequestedAmount".equals(setting.getName()) && Boolean.TRUE.equals(setting.getValue()))
.findFirst()
.ifPresent(setting -> {
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
if(fieldValue!=null) {
try {
BigDecimal amountRequested = new BigDecimal(fieldValue.toString());
applicationFormEntity.getApplication().setAmountRequested(amountRequested);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Field value is not a valid number: " + fieldValue, e);
}
}
});
ApplicationFormFieldEntity oldApplicationFormFieldData = null;
@@ -539,6 +547,7 @@ public class ApplicationDao {
}
}
}
calculationProcessForFormula(applicationFormEntity,contentResponseBeans,applicationFormFieldRequestBean,fieldValidator);
Utils.setIfUpdated(applicationFormFieldEntity::getFieldId, applicationFormFieldEntity::setFieldId, applicationFormFieldRequestBean.getFieldId());
if (applicationFormFieldRequestBean.getFieldValue() != null) {
@@ -561,7 +570,6 @@ public class ApplicationDao {
VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplicationFormFieldData).newData(applicationFormField).build());
log.info("Version history logged for action: {}, Field ID: {}", actionType, applicationFormFieldEntity.getFieldId());
return applicationFormField;
}
@@ -670,7 +678,7 @@ public class ApplicationDao {
return documentIds;
}
private List<Long> validateDocumentIds(String documentId) {
public List<Long> validateDocumentIds(String documentId) {
if (documentId != null && !documentId.isEmpty()) {
return Arrays.stream(documentId.split(","))
.map(Long::parseLong)
@@ -819,7 +827,7 @@ public class ApplicationDao {
if(formApplicationResponse.getContent() != null && formApplicationResponse.getFormFields() != null) {
formApplicationResponses.add(formApplicationResponse);
}
}
public FormApplicationResponse processForm(FormEntity formEntity, ApplicationEntity applicationEntity) {
@@ -879,6 +887,10 @@ public class ApplicationDao {
checkCallEndDate(call);
// call = callService.validatePublishedCall(call.getId());
// checkIfApplicationExists(call, userWithCompanyEntity, userEntity);
HubEntity hubEntity = hubService.valdateHub(call.getHub().getId());
if(hubEntity.getUniqueUuid().equals(defaultHubUuid)){
checkIfApplicationExists(call, userWithCompanyEntity, userEntity);
}
ApplicationEntity applicationEntity = createApplicationEntity(userEntity, call, userWithCompanyEntity);
applicationEntity.setComments(applicationRequest.getComments());
applicationEntity = saveApplicationEntity(applicationEntity);
@@ -891,6 +903,18 @@ public class ApplicationDao {
// }
// }
public void checkIfApplicationExists(CallEntity call, UserWithCompanyEntity userWithCompanyEntity, UserEntity userEntity){
List<ApplicationEntity> applications = applicationRepository.findByUserIdAndUserWithCompany_IdAndCall_IdAndIsDeletedFalseAndStatusNot(
userEntity.getId(), userWithCompanyEntity.getId(), call.getId(), ApplicationStatusTypeEnum.REJECTED.name()
);
if (!applications.isEmpty()) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
}
}
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
@@ -955,7 +979,7 @@ public class ApplicationDao {
return (int) Math.round(progress);
}
public void validateFormFields(ApplicationRequestBean request, FormEntity formEntity) {
// List<ContentResponseBean> contentResponseBeans=Utils.convertJsonStringToList(formEntity.getContent(),ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans=formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
@@ -1035,7 +1059,7 @@ public class ApplicationDao {
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_USER_AND_COMPANY,
hub, null);
// Create the map for subject placeholders
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
@@ -1108,15 +1132,28 @@ public class ApplicationDao {
// mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
// mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
// mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
if(validator.isProductionProfileActivated()) {
emailLogRequest.setRecipientEmails(carloEmail);
// mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(carloEmail),emailLogRequest);
}
// if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(defaultHubUuid))) {
// if (validator.isProductionProfileActivated()) {
// emailLogRequest.setRecipientEmails(carloEmail);
//// mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
// emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(carloEmail),emailLogRequest);
// }
// List<String> listDefaultSystemReceiverEmail = Arrays.stream(defaultSystemReceiverEmail.split(","))
// .map(String::trim)
// .filter(email -> !email.isEmpty())
// .toList();
//
// emailLogRequest.setRecipientEmails(defaultSystemReceiverEmail);
// emailNotificationDao.sendMail(hub.getId(), subject, body, listDefaultSystemReceiverEmail, emailLogRequest);
// }
List<String> hubEmails = Arrays.stream(hub.getEmail().split(","))
.map(String::trim)
.filter(email -> !email.isEmpty())
.toList();
emailLogRequest.setRecipientEmails(hub.getEmail());
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(hub.getEmail()),emailLogRequest);
emailLogRequest.setRecipientEmails(defaultSystemReceiverEmail);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(defaultSystemReceiverEmail),emailLogRequest);
emailNotificationDao.sendMail(hub.getId(), subject, body,hubEmails,emailLogRequest);
emailLogRequest.setRecipientEmails(rinaldoEmail);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(rinaldoEmail),emailLogRequest);
}
@@ -1212,17 +1249,17 @@ public class ApplicationDao {
}
public ApplicationSignedDocumentResponse getSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
// validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
if (validator.checkIsPreInstructor()) {
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluationByApplicationId(applicationId);
validator.validatePreInstructor(request, applicationEvaluationEntity.getUserId());
} else {
validator.validateUserId(request, applicationEntity.getUserId());
}
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
@@ -1231,11 +1268,11 @@ public class ApplicationDao {
}
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
public void deleteSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
//cloned entity for old data
@@ -1263,9 +1300,12 @@ public class ApplicationDao {
if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.DRAFT.getValue().equals(applicationEntity.getStatus()))) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
}
if (applicationEntity.getAmountRequested() == null || applicationEntity.getAmountRequested().compareTo(BigDecimal.ZERO) <= 0 ) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.AMOUNT_REQUEST_SHOULD_GREATED_THEN_ZERO));
}
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalSteps = flowFormDao.calculateTotalSteps(flowEdgesList);
Integer completedSteps = flowFormDao.getCompletedSteps(applicationEntity);
Integer completedSteps = flowFormDao.getCompletedSteps(applicationEntity, true);
if (totalSteps.intValue() != completedSteps) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
@@ -1402,6 +1442,9 @@ 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);
if (applicationPageableRequestBean.getGlobalFilters() != null) {
pageNo = applicationPageableRequestBean.getGlobalFilters().getPage();
pageLimit = applicationPageableRequestBean.getGlobalFilters().getLimit();
@@ -1412,7 +1455,7 @@ public class ApplicationDao {
if (pageNo == null || pageNo <= 0) {
pageNo = GepafinConstant.DEFAULT_PAGE;
}
Specification<ApplicationEntity> spec = search(callId, companyId, applicationPageableRequestBean, userEntity);
Specification<ApplicationEntity> spec = search(callId,companyId, userWithCompany.getId(), applicationPageableRequestBean, userEntity);
Page<ApplicationEntity> entityPage = applicationRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
// Prepare the response
@@ -1435,10 +1478,10 @@ public class ApplicationDao {
return pageableResponseBean;
}
public Specification<ApplicationEntity> search(Long callId, Long companyId, ApplicationPageableRequestBean applicationPageableRequestBean, UserEntity userEntity) {
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, userEntity);
List<Predicate> predicates = getPredicates(applicationPageableRequestBean, criteriaBuilder, root, callId,companyId, userWithCompanyId, userEntity);
SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
if (applicationPageableRequestBean.getGlobalFilters() != null
@@ -1462,13 +1505,15 @@ public class ApplicationDao {
private List<Predicate> getPredicates(ApplicationPageableRequestBean applicationPageableRequestBean,
CriteriaBuilder criteriaBuilder, Root<ApplicationEntity> root, Long callId, Long companyId, UserEntity userEntity) {
CriteriaBuilder criteriaBuilder, Root<ApplicationEntity> root, Long callId,Long companyId, Long userWithCompanyId, UserEntity userEntity) {
Integer year = null;
String search = null;
Integer daysRange = null;
if (applicationPageableRequestBean.getGlobalFilters() != null) {
year = applicationPageableRequestBean.getGlobalFilters().getYear();
search = applicationPageableRequestBean.getGlobalFilters().getSearch();
daysRange = applicationPageableRequestBean.getDaysRange();
}
List<Predicate> predicates = new ArrayList<>();
@@ -1526,16 +1571,24 @@ public class ApplicationDao {
}
// 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));
}
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.HUB_ID), userEntity.getHub().getId()));
return predicates;
}
public void checkCallEndDate(CallEntity call) {
LocalDateTime now = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
@@ -1553,5 +1606,135 @@ public class ApplicationDao {
}
}
public void calculationProcessForFormula(ApplicationFormEntity applicationFormEntity, List<ContentResponseBean> contentResponseBeans, ApplicationFormFieldRequestBean applicationFormFieldRequestBean,FieldValidator fieldValidator) {
List<String> formulaValue = new ArrayList<>();
String formulaValueOpt=null;
String label=null;
for (ContentResponseBean contentResponseBean:contentResponseBeans){
if(contentResponseBean.getId().equals(applicationFormFieldRequestBean.getFieldId())){
for (SettingResponseBean settingResponseBean:contentResponseBean.getSettings()){
if (settingResponseBean.getName().equals("label")){
label= String.valueOf(settingResponseBean.getValue());
}
if(settingResponseBean.getName().equals("formula")){
String value= (String) settingResponseBean.getValue();
formulaValueOpt=value;
formulaValue=Utils.extractValues(value);
}
}
}
}
Map<String, String> mappedFormulaValue = new HashMap<>();
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
if (formulaValueOpt != null && fieldValue==null) {
fieldValue=0;
}
for (ContentResponseBean contentResponseBean : contentResponseBeans) {
String contentId = contentResponseBean.getId();
// Extract variable values once per contentResponseBean to avoid repeated stream operations
Set<String> variableValues = contentResponseBean.getSettings().stream()
.filter(setting -> "variable".equals(setting.getName()))
.flatMap(setting -> {
Object value = setting.getValue(); // Get the raw value
if (value instanceof String) {
return Stream.of((String) value); // Handle single String case
} else if (value instanceof List) {
return ((List<?>) value).stream()
.filter(item -> item instanceof String) // Ensure it's a String
.map(item -> (String) item); // Convert to String
} else {
return Stream.empty(); // Ignore unexpected types
}
})
.collect(Collectors.toSet()); // Collect into a Set for uniqueness
for (String formula : formulaValue) {
if (variableValues.contains(formula)) { // O(1) lookup instead of O(n)
mappedFormulaValue.put(formula, contentId);
}
}
}
Map<String, String> updatedMappedFormulaValue = new HashMap<>();
for (Map.Entry<String, String> entry : mappedFormulaValue.entrySet()) {
String variable = entry.getKey();
String contentId = entry.getValue();
// Repository call using contentId
Optional<ApplicationFormFieldEntity> optionalEntity = applicationFormFieldRepository.findByApplicationFormIdAndFieldId(applicationFormEntity.getId(),contentId);
// If entity is found, extract fieldValue and fieldId
optionalEntity.ifPresent(entity -> {
String entityFieldValue = entity.getFieldValue(); // Assuming getter method exists
String fieldId = entity.getFieldId(); // Assuming getter method exists
String tableType = contentResponseBeans.stream()
.filter(content -> content.getId().equals(fieldId)) // Match Content ID with fieldId
.flatMap(content -> content.getSettings().stream()) // Extract settings
.filter(setting -> "criteria_table_columns".equals(setting.getName())) // Match name
.map(setting -> setting.getName()) // Return the name of the setting
.findFirst() // Get the first match
.orElse(null); // Default to null if no match
if(tableType!=null){
JSONObject jsonObject = new JSONObject(entityFieldValue);
// Extract the value of total
entityFieldValue = jsonObject.getString("total");
}
updatedMappedFormulaValue.put(fieldId, entityFieldValue);
});
}
if(formulaValueOpt==null || formulaValueOpt.isEmpty()){
return;
}
double finalValue = evaluateFormula(formulaValueOpt, mappedFormulaValue, updatedMappedFormulaValue);
fieldValidator.formulaValidation(fieldValue, finalValue, label);
}
public static double evaluateFormula(String formula, Map<String, String> mappedFormulaValue, Map<String, String> updatedMappedFormulaValue) {
// Step 1: Extract all placeholders (variables) like {rest}, {another_var}, etc.
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher matcher = pattern.matcher(formula);
List<String> variables = new ArrayList<>();
while (matcher.find()) {
variables.add(matcher.group(1)); // Extract variable names inside the curly braces
}
// Step 2: Replace placeholders with corresponding fieldValue
Map<String, Double> variableValues = new HashMap<>();
for (String variable : variables) {
String fieldId = mappedFormulaValue.get(variable);
if (fieldId != null && updatedMappedFormulaValue.containsKey(fieldId)) {
String fieldValueStr = updatedMappedFormulaValue.get(fieldId);
try {
double fieldValue = Double.parseDouble(fieldValueStr); // Assuming fieldValue is numeric
variableValues.put(variable, fieldValue);
} catch (NumberFormatException e) {
// Handle invalid number format gracefully (e.g., log an error or default to 0)
variableValues.put(variable, 0.0);
}
}
}
// Step 3: Replace variables in the formula with their corresponding values
String expression = formula;
for (String variable : variables) {
Double value = variableValues.get(variable);
if (value != null) {
// Replace {variable} with its corresponding value in the formula
expression = expression.replace("{" + variable + "}", String.valueOf(value));
}
}
// Step 4: Evaluate the mathematical expression
return Utils.evaluateExpression(expression);
}
}