diff --git a/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java b/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java index f696cdb0..c2e648ce 100644 --- a/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java +++ b/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java @@ -423,6 +423,19 @@ public class GepafinConstant { public static final String FORMULA_AMOUNT_NOT_MATCHED="formula.amount.not.matches.requested.amount"; public static final String CRITERIA_TABLE_COLUMNS="criteria_table_columns"; + public static final String LABEL="label"; + public static final String FORMULA="formula"; + public static final String VARIABLE="variable"; + public static final String TOTAL="total"; + public static final String NUMBER_INPUT="numberinput"; + public static final String CHECK_BOXES="checkboxes"; + public static final String VALIDATION_FIELD_MAX = "validation.field.max_value"; + public static final String VALIDATION_FIELD_MIN = "validation.field.min_value"; + public static final String VALIDATION_FIELD_MAX_CHECK_BOX = "validation.field.max.checkbox"; + public static final String VALIDATION_FIELD_MIN_CHECK_BOX = "validation.field.min.checkbox"; + + + } diff --git a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationEvaluationDao.java b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationEvaluationDao.java index ef01dea6..b26c007b 100644 --- a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationEvaluationDao.java +++ b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationEvaluationDao.java @@ -17,6 +17,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationExceptio import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException; import net.gepafin.tendermanagement.web.rest.api.errors.Status; import org.apache.commons.lang3.StringUtils; +import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @@ -29,6 +30,7 @@ import java.time.temporal.ChronoUnit; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; import static net.gepafin.tendermanagement.util.Utils.log; import static net.gepafin.tendermanagement.util.Utils.setIfUpdated; @@ -1968,7 +1970,9 @@ public class ApplicationEvaluationDao { //Handling Application Evaluation form EvaluationFormEntity evaluationFormEntity = evaluationFormService.validateEvaluationForm(evaluationFormId); validateFormFields(applicationEvaluationFormRequestBean,evaluationFormEntity); +// formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity); // ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationRepository.findByAssignedApplicationsId(assignedApplicationId); + validateFormFieldCustom(applicationEvaluationFormRequestBean.getFormFields(),entity,evaluationFormEntity); ApplicationEvaluationFormEntity applicationEvaluationFormEntity = getApplicationEvaluationFormOrCreate(evaluationFormEntity,entity); createOrUpdateMultipleFormFields(applicationEvaluationFormRequestBean.getFormFields(), applicationEvaluationFormEntity, evaluationFormEntity); return processEvaluationForm(entity); @@ -2024,17 +2028,20 @@ public class ApplicationEvaluationDao { public List createOrUpdateMultipleFormFields(List formFieldRequestBeans, ApplicationEvaluationFormEntity applicationEvaluationFormEntity, EvaluationFormEntity evaluationFormEntity) { + FieldValidator fieldValidator = FieldValidator.create(); List existingFields = applicationEvaluationFormFieldRepository.findByApplicationEvaluationFormId(applicationEvaluationFormEntity.getId()); - return formFieldRequestBeans.stream().map(requestBean -> createOrUpdateApplicationEvaluationFormField(requestBean, applicationEvaluationFormEntity, existingFields, evaluationFormEntity)) + List applicationEvaluationFormFieldEntities= formFieldRequestBeans.stream().map(requestBean -> createOrUpdateApplicationEvaluationFormField(requestBean, applicationEvaluationFormEntity, existingFields, evaluationFormEntity,fieldValidator)) .collect(Collectors.toList()); + fieldValidator.validate(); + return applicationEvaluationFormFieldEntities; } public ApplicationEvaluationFormFieldEntity createOrUpdateApplicationEvaluationFormField(ApplicationFormFieldRequestBean applicationFormFieldRequestBean, ApplicationEvaluationFormEntity applicationEvaluationFormEntity, List applicationEvaluationFormFieldEntities, - EvaluationFormEntity evaluationFormEntity){ + EvaluationFormEntity evaluationFormEntity,FieldValidator fieldValidator){ ApplicationEvaluationFormFieldEntity applicationEvaluationFormFieldEntity = new ApplicationEvaluationFormFieldEntity(); validateFileUploadDocuments(applicationFormFieldRequestBean, evaluationFormEntity); VersionActionTypeEnum actionType = VersionActionTypeEnum.INSERT; @@ -2057,7 +2064,8 @@ public class ApplicationEvaluationDao { } } Utils.setIfUpdated(applicationEvaluationFormFieldEntity::getFieldId, applicationEvaluationFormFieldEntity::setFieldId, applicationFormFieldRequestBean.getFieldId()); - + List contentBeans = Utils.convertJsonStringToList(evaluationFormEntity.getContent(), ContentResponseBean.class); + calculationProcessForFormula(applicationEvaluationFormEntity,contentBeans,applicationFormFieldRequestBean,fieldValidator); if (applicationFormFieldRequestBean.getFieldValue() != null) { applicationEvaluationFormFieldEntity.setFieldValue(Utils.convertObjectToJsonString(applicationFormFieldRequestBean.getFieldValue())); } else { @@ -2266,5 +2274,150 @@ public class ApplicationEvaluationDao { return request; } + + public void calculationProcessForFormula(ApplicationEvaluationFormEntity applicationFormEntity, List contentResponseBeans, ApplicationFormFieldRequestBean applicationFormFieldRequestBean,FieldValidator fieldValidator) { + List 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(GepafinConstant.LABEL)){ + label= String.valueOf(settingResponseBean.getValue()); + } + + if(settingResponseBean.getName().equals(GepafinConstant.FORMULA)){ + String value= (String) settingResponseBean.getValue(); + formulaValueOpt=value; + formulaValue=Utils.extractValues(value); + } + } + } + } + Map 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 variableValues = contentResponseBean.getSettings().stream() + .filter(setting -> GepafinConstant.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 updatedMappedFormulaValue = new HashMap<>(); + + for (Map.Entry entry : mappedFormulaValue.entrySet()) { + String variable = entry.getKey(); + String contentId = entry.getValue(); + + // Repository call using contentId + Optional optionalEntity = applicationEvaluationFormFieldRepository.findByApplicationEvaluationFormIdAndFieldIdAndIsDeletedFalse(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 -> GepafinConstant.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(GepafinConstant.TOTAL); + + } + + updatedMappedFormulaValue.put(fieldId, entityFieldValue); + }); + } + if(formulaValueOpt==null || formulaValueOpt.isEmpty()){ + return; + } + double finalValue = applicationDao.evaluateFormula(formulaValueOpt, mappedFormulaValue, updatedMappedFormulaValue); + + fieldValidator.formulaValidation(fieldValue, finalValue, label); + } + public void validateFormFieldCustom(List applicationFormFieldRequestList, ApplicationEvaluationEntity applicationEvaluationEntity, EvaluationFormEntity evaluationFormEntity) { + Map formFieldMap = new LinkedHashMap(); + for(ApplicationFormFieldRequestBean applicationFormFieldRequestBean:applicationFormFieldRequestList) { + if(applicationFormFieldRequestBean.getFieldValue()==null ) + continue; + if (applicationFormFieldRequestBean.getFieldValue() != null ) { + Object fieldValue = applicationFormFieldRequestBean.getFieldValue(); +// formDao.checkObjectData(applicationFormFieldRequestBean.getFieldId(), fieldValue, formFieldMap); + if (fieldValue instanceof List) { + List list = (List) fieldValue; + + // Only map if the list is not empty and contains Strings + if (!list.isEmpty() && list.get(0) instanceof String) { + for (Object value : list) { + formDao.setFormFieldMap(applicationFormFieldRequestBean.getFieldId(), formFieldMap, value); + } + }else if (list.stream().allMatch(item -> item instanceof Map map && + map.keySet().stream().allMatch(String.class::isInstance))) { + if (fieldValue != null) { + formFieldMap.put(applicationFormFieldRequestBean.getFieldId(), fieldValue); + } + } else formDao.setFormFieldMap(applicationFormFieldRequestBean.getFieldId(), formFieldMap, fieldValue); + } + else { + formDao.setFormFieldMap(applicationFormFieldRequestBean.getFieldId(), formFieldMap, fieldValue); + } + }} + + EvaluationFormResponseBean evaluationFormResponseBean = evaluationFormDao.convertEvaluationFormEntityToEvaluationFormResponseBean(evaluationFormEntity); + ApplicationEvaluationFormEntity applicationEvaluationForm=applicationEvaluationFormRepository.findByEvaluationIdAndEvaluationFormId(applicationEvaluationEntity.getId(),evaluationFormEntity.getId()); + Boolean isApplicationFormExist= getApplicationEvaluationFormExist(applicationEvaluationForm); + FieldValidator validator = FieldValidator.create(); + evaluationFormResponseBean.getContent().forEach(contentResponseBean -> { + String fieldId = contentResponseBean.getId(); + String fieldLabel=contentResponseBean.getLabel(); + Object object=formFieldMap.get(fieldId); + String value =Utils.convertToStringForFormFieldValue(object); + if(value == null && isApplicationFormExist) { + return; + } + FieldValidatorBean fieldValidatorBean = Utils.convertSourceObjectToDestinationObject(contentResponseBean.getValidators(), FieldValidatorBean.class); + validator + .minLength(value, fieldValidatorBean.getMinLength(), fieldLabel,fieldValidatorBean.getMin(),contentResponseBean) // Only applies if minLength is not null + .maxLength(value, fieldValidatorBean.getMaxLength(), fieldLabel,fieldValidatorBean.getMax(),contentResponseBean) // Only applies if maxLength is not null + .matchesPattern(value, fieldValidatorBean.getPattern(), fieldLabel) // Only applies if pattern is present + .validateCustom(value, fieldValidatorBean.getCustom(), fieldLabel,contentResponseBean); // Add the custom validation here + }); + validator.validate(); + } + private Boolean getApplicationEvaluationFormExist(ApplicationEvaluationFormEntity applicationEvaluationFormEntity) { + if(applicationEvaluationFormEntity !=null) { + return true; + } + return false; + } } diff --git a/src/main/java/net/gepafin/tendermanagement/dao/FormDao.java b/src/main/java/net/gepafin/tendermanagement/dao/FormDao.java index 4311076f..702a3b44 100644 --- a/src/main/java/net/gepafin/tendermanagement/dao/FormDao.java +++ b/src/main/java/net/gepafin/tendermanagement/dao/FormDao.java @@ -415,8 +415,8 @@ public class FormDao { } FieldValidatorBean fieldValidatorBean = Utils.convertSourceObjectToDestinationObject(contentResponseBean.getValidators(), FieldValidatorBean.class); validator - .minLength(value, fieldValidatorBean.getMinLength(), fieldLabel) // Only applies if minLength is not null - .maxLength(value, fieldValidatorBean.getMaxLength(), fieldLabel) // Only applies if maxLength is not null + .minLength(value, fieldValidatorBean.getMinLength(), fieldLabel,fieldValidatorBean.getMin(),contentResponseBean) // Only applies if minLength is not null + .maxLength(value, fieldValidatorBean.getMaxLength(), fieldLabel,fieldValidatorBean.getMax(),contentResponseBean) // Only applies if maxLength is not null .matchesPattern(value, fieldValidatorBean.getPattern(), fieldLabel) // Only applies if pattern is present .validateCustom(value, fieldValidatorBean.getCustom(), fieldLabel,contentResponseBean); // Add the custom validation here if (fieldValidatorBean.getCustom() != null && fieldValidatorBean.getCustom().equals(GepafinConstant.IS_PIVA)) { @@ -429,28 +429,34 @@ public class FormDao { validator.validate(); } - private void checkObjectData(String fieldId, Object fieldValue, Map formFieldMap) { - if (fieldValue instanceof List) { + public void checkObjectData(String fieldId, Object fieldValue, Map formFieldMap) { + if (fieldValue instanceof List) { List list = (List) fieldValue; // Only map if the list is not empty and contains Strings - if (!list.isEmpty() && list.get(0) instanceof String) { + if (list.stream().allMatch(item -> item instanceof String)) { + formFieldMap.put(fieldId, list); + } + else if (!list.isEmpty() && list.get(0) instanceof String) { for (Object value : list) { setFormFieldMap(fieldId, formFieldMap, value); } - }else if (list.stream().allMatch(item -> item instanceof Map map && + } + else if (list.stream().allMatch(item -> item instanceof Map map && map.keySet().stream().allMatch(String.class::isInstance))) { if (fieldValue != null) { formFieldMap.put(fieldId, fieldValue); } } else setFormFieldMap(fieldId, formFieldMap, fieldValue); } + else setFormFieldMap(fieldId, formFieldMap, fieldValue); } - private void setFormFieldMap(String fieldId, Map formFieldMap, Object value) { - if (value instanceof String) { - if(value !=null && Boolean.FALSE.equals(StringUtils.isEmpty((String)value))) { + public void setFormFieldMap(String fieldId, Map formFieldMap, Object value) { + if(value !=null){ + String fieldValue= String.valueOf(value); + if(Boolean.FALSE.equals(StringUtils.isEmpty(fieldValue))) { formFieldMap.put(fieldId, value); - } + } } } diff --git a/src/main/java/net/gepafin/tendermanagement/model/request/FieldValidatorBean.java b/src/main/java/net/gepafin/tendermanagement/model/request/FieldValidatorBean.java index be94ffc0..3c199589 100644 --- a/src/main/java/net/gepafin/tendermanagement/model/request/FieldValidatorBean.java +++ b/src/main/java/net/gepafin/tendermanagement/model/request/FieldValidatorBean.java @@ -11,6 +11,10 @@ public class FieldValidatorBean { private Long maxLength; + private Long min; + + private Long max; + private String pattern; private String custom; diff --git a/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationEvaluationFormFieldRepository.java b/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationEvaluationFormFieldRepository.java index 07a0d318..ea12bd96 100644 --- a/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationEvaluationFormFieldRepository.java +++ b/src/main/java/net/gepafin/tendermanagement/repositories/ApplicationEvaluationFormFieldRepository.java @@ -7,6 +7,7 @@ import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Optional; @Repository public interface ApplicationEvaluationFormFieldRepository extends JpaRepository { @@ -15,4 +16,16 @@ public interface ApplicationEvaluationFormFieldRepository extends JpaRepository< "AND f.isDeleted = false") List findByApplicationEvaluationFormId( @Param("applicationEvaluationFormId") Long applicationEvaluationFormId); + + Optional findByApplicationEvaluationFormIdAndFieldIdAndIsDeletedFalse(Long applicationEvaluationFormId, String fieldId); + + @Query("SELECT f FROM ApplicationEvaluationFormFieldEntity f " + + "WHERE f.applicationEvaluationForm.id = :applicationEvaluationFormId " + + "AND f.fieldId IN :fieldIds " + + "AND f.isDeleted = false") + List findByApplicationEvaluationFormIdAndFieldIds( + @Param("applicationEvaluationFormId") Long applicationEvaluationFormId, + @Param("fieldIds") List fieldIds); + + } diff --git a/src/main/java/net/gepafin/tendermanagement/util/FieldValidator.java b/src/main/java/net/gepafin/tendermanagement/util/FieldValidator.java index 7a4e24b8..fa881383 100644 --- a/src/main/java/net/gepafin/tendermanagement/util/FieldValidator.java +++ b/src/main/java/net/gepafin/tendermanagement/util/FieldValidator.java @@ -59,16 +59,56 @@ public class FieldValidator { throw new ValidationException(Status.VALIDATION_ERROR, errors, Translator.toLocale(GepafinConstant.VALIDATION_MESSAGE)); } } - public FieldValidator minLength(String value, Long minLength, String fieldLabel) { - if (minLength != null && value != null && value.length() < minLength) { - errors.add(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MIN_LENGTH), fieldLabel, minLength)); - } + public FieldValidator minLength(String value, Long minLength, String fieldLabel,Long min,ContentResponseBean contentResponseBean) { + if (value != null) { + if(min!=null) { + if(contentResponseBean.getName().equals(GepafinConstant.NUMBER_INPUT)) { + long numericValue = Long.parseLong(value); // Convert String to Long + if (numericValue < min) { + errors.add(MessageFormat.format( + Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MIN), fieldLabel, min)); + } + } + else if(contentResponseBean.getName().equals(GepafinConstant.CHECK_BOXES)){ + List check = Utils.convertJsonStringToList(value,String.class); + if (check== null || check.size() < min) { + errors.add(MessageFormat.format( + Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MIN_CHECK_BOX), fieldLabel, min)); + } + } + } + if(minLength!=null) { + if (value.length() < minLength) { + errors.add(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MIN_LENGTH), fieldLabel, minLength)); + } + } + } return this; } - public FieldValidator maxLength(String value, Long maxLength, String fieldLabel) { - if (maxLength != null && value != null && value.length() > maxLength) { - errors.add(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MAX_LENGTH), fieldLabel, maxLength)); + public FieldValidator maxLength(String value, Long maxLength, String fieldLabel, Long max, ContentResponseBean contentResponseBean) { + if (value != null) { + if (max != null) { + if(contentResponseBean.getName().equals(GepafinConstant.NUMBER_INPUT)) { + long numericValue = Long.parseLong(value); // Convert String to Long + if (numericValue > max) { + errors.add(MessageFormat.format( + Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MAX), fieldLabel, max)); + } + } + else if(contentResponseBean.getName().equals(GepafinConstant.CHECK_BOXES)){ + List check = Utils.convertJsonStringToList(value,String.class); + if (check== null || check.size() > max) { + errors.add(MessageFormat.format( + Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MAX_CHECK_BOX), fieldLabel, max)); + } + } + } + if (maxLength != null) { + if (value.length() > maxLength) { + errors.add(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_FIELD_MAX_LENGTH), fieldLabel, maxLength)); + } + } } return this; } @@ -167,12 +207,12 @@ public class FieldValidator { switch (customRule) { case GepafinConstant.NON_EMPTY_TABLES: - try { - checkTableValidation(value, fieldId, contentResponseBean, errors); - } catch (Exception e) { - throw new RuntimeException(e); - } - break; + try { + checkTableValidation(value, fieldId, contentResponseBean, errors); + } catch (Exception e) { + throw new RuntimeException(e); + } + break; } return this; @@ -187,13 +227,13 @@ public class FieldValidator { .orElse(null); // Default to null if no match if (tableType!=null){ - try { + try { Object object = PdfUtils.extractRows(value);; value= Utils.convertToString(object); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + } catch (Exception e) { + throw new RuntimeException(e); + } + } contentResponseBean.getSettings().stream() .filter(setting -> "table_columns".equals(setting.getName()) || GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(setting.getName())) // Check for "table_columns" diff --git a/src/main/resources/message_en.properties b/src/main/resources/message_en.properties index 7aab6f08..159209d3 100644 --- a/src/main/resources/message_en.properties +++ b/src/main/resources/message_en.properties @@ -166,6 +166,11 @@ validation.field.max_length=Field {0} must be no more than {1} characters long. validation.field.pattern=Field {0} does not match the required pattern. validation.field.not_null=Field {0} must not be null. validation.field.not_empty=Field {0} must not be empty. +validation.field.max_value=Field {0} must be no more than {1}. +validation.field.min_value=Field {0} must be greater than {1}. +validation.field.min.checkbox=Field {0} should be checked for atleast {1}. +validation.field.max.checkbox=Field {0} should have only {1} checked. + current.form.incomplete=Current form is not filled. flow.not.found=Flow not found. @@ -372,3 +377,4 @@ company.id.not.null=Company ID cannot be null. formula.amount.not.matches.requested.amount= The {0} does not matches to calculated amount. + diff --git a/src/main/resources/message_it.properties b/src/main/resources/message_it.properties index c1794a8d..d51d07c1 100644 --- a/src/main/resources/message_it.properties +++ b/src/main/resources/message_it.properties @@ -160,6 +160,11 @@ validation.field.max_length=Il campo {0} deve essere lungo al massimo {1} caratt validation.field.pattern=Il campo {0} non corrisponde al modello richiesto. validation.field.not_null=Il campo {0} non deve essere nullo. validation.field.not_empty=Il campo {0} non deve essere vuoto. +validation.field.max_value=Il campo {0} non deve essere pił grande di {1}. +validation.field.min_value=Il campo {0} deve essere maggiore di {1}. +validation.field.min.checkbox=Il campo {0} dovrebbe essere controllato almeno per {1}. +validation.field.max.checkbox=Il campo {0} dovrebbe avere solo {1} selezionato. + current.form.incomplete=il modulo corrente non ? compilato flow.not.found=Flow not found. validation.message=Messaggi di convalida.