Merge pull request #20 from Kitzanos/call-api-validation

Added few validation in call
This commit is contained in:
rajeshkhore
2024-09-13 18:48:52 +05:30
committed by GitHub
18 changed files with 210 additions and 58 deletions

View File

@@ -108,4 +108,5 @@ public class GepafinConstant {
public static final String FLOW_FETCHED_SUCCESSFULLY="flow.fetched.successfully";
public static final String FLOW_ALREADY_EXISTS="flow.already.exists";
public static final String FLOW_REQUEST_NOT_PROPER="flow.request.not.complete";
public static final String FLOW_NOT_FOUND = "flow.not.found";
}

View File

@@ -3,13 +3,20 @@ package net.gepafin.tendermanagement.dao;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.service.FaqService;
import net.gepafin.tendermanagement.service.LookUpDataService;
import net.gepafin.tendermanagement.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -39,13 +46,14 @@ import net.gepafin.tendermanagement.repositories.DocumentRepository;
import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository;
import net.gepafin.tendermanagement.repositories.FaqRepository;
import net.gepafin.tendermanagement.repositories.RegionRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.service.impl.CallValidatorServiceImpl;
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 static net.gepafin.tendermanagement.enums.RoleStatusEnum.ROLE_SUPER_ADMIN;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole;
@Component
public class CallDao {
@@ -64,7 +72,7 @@ public class CallDao {
@Autowired
private RegionRepository regionRepository;
@Autowired
private LookUpDataService lookUpDataService;
@@ -73,20 +81,24 @@ public class CallDao {
@Autowired
private UserService userService;
@Autowired
private FaqService faqService;
@Autowired
private FlowDao flowDao;
@Autowired
private FormDao formDao;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) {
UserEntity userEntity = userService.validateUser(userId);
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
CallEntity callEntity = convertToCallEntity(createCallRequest);
updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ);
convertLookUpDataEntities(createCallRequest.getAimedTo(), callEntity,
LookUpDataTypeEnum.AIMED_TO);
CallResponse createCallResponseBean = getCallResponseBean(callEntity);
createCallResponseBean.setCurrentStep(GepafinConstant.STEP_1);
return createCallResponseBean;
@@ -391,12 +403,12 @@ public class CallDao {
public void isValidDateRange(UpdateCallRequestStep1 updateCallRequest, CallEntity callEntity) {
List<LocalDateTime> dates = updateCallRequest.getDates();
LocalDate startDate = (dates != null && dates.size() > 0 && dates.get(0) != null)
? dates.get(0).toLocalDate()
LocalDate startDate = (dates != null && dates.size() > 0 && dates.get(0) != null)
? dates.get(0).toLocalDate()
: null;
LocalDate endDate = (dates != null && dates.size() > 1 && dates.get(1) != null)
? dates.get(1).toLocalDate()
LocalDate endDate = (dates != null && dates.size() > 1 && dates.get(1) != null)
? dates.get(1).toLocalDate()
: null;
Boolean isValid = true;
@@ -427,7 +439,7 @@ public class CallDao {
setIfUpdated(callEntity::getDescriptionLong, callEntity::setDescriptionLong,
updateCallRequest.getDescriptionLong());
List<LocalDateTime> dates=updateCallRequest.getDates();
if (dates != null && dates.size()>1) {
if (dates.size() > 0) {
setIfUpdated(callEntity::getStartDate, callEntity::setStartDate, dates.get(0));
@@ -545,9 +557,14 @@ public class CallDao {
return createCallResponseBean;
}
public List<CallDetailsResponseBean> getAllCalls() {
return callRepository.findAll()
.stream()
public List<CallDetailsResponseBean> getAllCalls(UserEntity user) {
String type=user.getRoleEntity().getRoleType();
List<String> callStatusList =CallStatusEnum.getStatusValues();
if (Boolean.FALSE.equals(ROLE_SUPER_ADMIN.getValue().equals(type))) {
callStatusList = List.of(CallStatusEnum.PUBLISH.getValue());
}
List<CallEntity> calls = callRepository.findByStatusIn(callStatusList);
return calls.stream()
.map(this::convertToCallDetailsResponseBean)
.collect(Collectors.toList());
}
@@ -555,7 +572,9 @@ public class CallDao {
public CallResponse validateCallData(CallEntity callEntity) {
validateUpdate(callEntity);
CallResponse callResponseBean = getCallResponseBean(callEntity);
CallValidatorServiceImpl.validateResponse(callResponseBean);
FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId());
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity.getId());
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean);
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
callRepository.save(callEntity);
callResponseBean.setCurrentStep(GepafinConstant.VALIDATE_REQUEST);

View File

@@ -30,6 +30,8 @@ public class FormFieldDao {
FormFieldEntity formFieldEntity = new FormFieldEntity();
formFieldEntity.setLabel(formFieldRequest.getLabel());
formFieldEntity.setName(formFieldRequest.getName());
formFieldEntity.setDescription(formFieldRequest.getDescription());
formFieldEntity.setSortOrder(formFieldRequest.getSortOrder());
formFieldEntity.setValidators(Utils.convertMapIntoJsonString(formFieldRequest.getValidators()));
formFieldEntity.setSettings(setSettingRequestBean(formFieldRequest.getSettings()));
formFieldEntity = saveFormFieldEntity(formFieldEntity);
@@ -40,6 +42,8 @@ public class FormFieldDao {
FormFieldResponseBean formFieldResponseBean = new FormFieldResponseBean();
formFieldResponseBean.setId(formFieldEntity.getId());
formFieldResponseBean.setName(formFieldEntity.getName());
formFieldResponseBean.setDescription(formFieldEntity.getDescription());
formFieldResponseBean.setSortOrder(formFieldEntity.getSortOrder());
formFieldResponseBean
.setSettings(Utils.convertJsonStringToList(formFieldEntity.getSettings(), SettingResponseBean.class));
formFieldResponseBean.setLabel(formFieldEntity.getLabel());
@@ -69,6 +73,8 @@ public class FormFieldDao {
FormFieldEntity formFieldEntity = validateFormField(formFieldId);
Utils.setIfUpdated(formFieldEntity::getName, formFieldEntity::setName, formFieldRequest.getName());
Utils.setIfUpdated(formFieldEntity::getLabel, formFieldEntity::setLabel, formFieldRequest.getLabel());
Utils.setIfUpdated(formFieldEntity::getDescription, formFieldEntity::setDescription, formFieldRequest.getDescription());
Utils.setIfUpdated(formFieldEntity::getSortOrder, formFieldEntity::setSortOrder, formFieldRequest.getSortOrder());
Utils.setIfUpdated(formFieldEntity::getSettings, formFieldEntity::setSettings,
setSettingRequestBean(formFieldRequest.getSettings()));
Utils.setIfUpdated(formFieldEntity::getValidators, formFieldEntity::setValidators,

View File

@@ -25,4 +25,10 @@ public class FormFieldEntity extends BaseEntity{
@Column(name = "VALIDATORS")
private String validators;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "SORT_ORDER")
private Integer sortOrder;
}

View File

@@ -1,7 +1,12 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public enum CallStatusEnum {
DRAFT("DRAFT"),
@@ -19,4 +24,19 @@ public enum CallStatusEnum {
public String getValue() {
return value;
}
@JsonCreator
public static CallStatusEnum fromValue(String value) {
for (CallStatusEnum b : CallStatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static List<String> getStatusValues() {
return Arrays.stream(CallStatusEnum.values())
.map(CallStatusEnum::getValue)
.collect(Collectors.toList());
}
}

View File

@@ -10,6 +10,10 @@ public class FormFieldRequest {
private String name;
private String description;
private Integer sortOrder;
private String label;
private List<SettingRequestBean> settings;

View File

@@ -14,6 +14,11 @@ public class FormFieldResponseBean {
private String label;
private String description;
private Integer sortOrder;
private List<SettingResponseBean> settings;
private Map<String,Object> validators;

View File

@@ -1,5 +1,6 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@@ -9,5 +10,5 @@ import java.util.List;
public interface CallRepository extends JpaRepository<CallEntity, Long> {
public CallEntity findByIdAndStatusNotIn(Long id, List<String> status);
List<CallEntity> findByStatusIn(List<String> callStatus);
}

View File

@@ -21,7 +21,7 @@ public interface CallService {
CallResponse getCallById (Long callId);
List<CallDetailsResponseBean> getAllCalls();
List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request);
CallResponse validateCallData(Long callId);

View File

@@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.dao.CallDao;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import net.gepafin.tendermanagement.model.request.CreateCallRequestStep1;
import net.gepafin.tendermanagement.model.request.CreateCallRequestStep2;
@@ -57,8 +58,10 @@ public class CallServiceImpl implements CallService {
@Override
@Transactional(readOnly = true)
public List<CallDetailsResponseBean> getAllCalls() {
return callDao.getAllCalls();
public List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
UserEntity user=tokenProvider.validateUser(userInfo);
return callDao.getAllCalls(user);
}

View File

@@ -1,44 +1,55 @@
package net.gepafin.tendermanagement.service.impl;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.model.response.CallResponse;
import net.gepafin.tendermanagement.model.response.FlowResponseBean;
import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
public class CallValidatorServiceImpl {
public static void validateResponse(CallResponse response) {
FieldValidator.create()
.notNull(response.getId(), "id")
.notNull(response.getName(), "name")
.notNull(response.getDescriptionShort(), "descriptionShort")
.notNull(response.getDescriptionLong(), "descriptionLong")
.notNull(response.getDates().get(0), "startDate")
.notNull(response.getDates().get(1), "endDate")
.notNull(response.getStatus(), "status")
.notNull(response.getRegionId(), "regionId")
.notNull(response.getAmount(), "amount")
.notNull(response.getAmountMax(), "amountMax")
.notNull(response.getThreshold(), "threshold")
.notNull(response.getDocumentationRequested(), "documentationRequested")
.notEmpty(response.getAimedTo(), "aimedTo")
.notEmpty(response.getCriteria(), "criteria")
.notEmpty(response.getDocs(), "docs")
.notEmpty(response.getFaq(), "faq")
.notEmpty(response.getImages(), "images")
.notEmpty(response.getCheckList(), "checkList")
.validate();
if (response.getDates().get(0).toLocalDate().isBefore(LocalDate.now())
|| response.getDates().get(1).toLocalDate().isBefore(LocalDate.now()) ||
response.getDates().get(0).toLocalDate().isAfter(response.getDates().get(1).toLocalDate())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_DATE_MSG));
}
}
public static void validateResponse(CallResponse response, FlowResponseBean flowResponse, List<FormResponseBean> formResponses) {
// Validate CallResponse (existing logic)
FieldValidator data = FieldValidator.create()
.notNull(response.getId(), "id")
.notNull(response.getName(), "name")
.notNull(response.getDescriptionShort(), "descriptionShort")
.notNull(response.getDescriptionLong(), "descriptionLong")
.notNull(response.getDates().get(0), "startDate")
.notNull(response.getDates().get(1), "endDate")
.notNull(response.getStatus(), "status")
.notNull(response.getRegionId(), "regionId")
.notNull(response.getAmount(), "amount")
.notNull(response.getAmountMax(), "amountMax")
.notNull(response.getThreshold(), "threshold")
.notNull(response.getDocumentationRequested(), "documentationRequested")
.notEmpty(response.getAimedTo(), "aimedTo")
.notEmpty(response.getCriteria(), "criteria")
.notEmpty(response.getDocs(), "docs")
.notEmpty(response.getFaq(), "faq")
.notEmpty(response.getImages(), "images")
.notEmpty(response.getCheckList(), "checkList");
if (response.getDates().get(0) == null || response.getDates().get(1) == null
|| response.getDates().get(0).toLocalDate().isBefore(LocalDate.now())
|| response.getDates().get(1).toLocalDate().isBefore(LocalDate.now())
|| response.getDates().get(0).toLocalDate().isAfter(response.getDates().get(1).toLocalDate())) {
data = data.addError(Translator.toLocale(GepafinConstant.INVALID_DATE_MSG));
}
if (flowResponse == null || ((flowResponse.getFlowData() == null || flowResponse.getFlowData().isEmpty())
&& (flowResponse.getFlowEdges() == null || flowResponse.getFlowEdges().isEmpty()))) {
data.addError(Translator.toLocale(GepafinConstant.FLOW_NOT_FOUND));
}
if (formResponses == null || formResponses.isEmpty()) {
data.addError(Translator.toLocale(GepafinConstant.FORM_NOT_FOUND));
}
data.validate();
}
}

View File

@@ -37,4 +37,9 @@ public class FieldValidator {
throw new ValidationException(Status.VALIDATION_ERROR, errors);
}
}
public FieldValidator addError( String errorMessage) {
errors.add(errorMessage);
return this;
}
}

View File

@@ -100,7 +100,7 @@ public interface CallApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "",
produces = { "application/json" })
ResponseEntity<Response<List<CallDetailsResponseBean>>> getAllCalls();
ResponseEntity<Response<List<CallDetailsResponseBean>>> getAllCalls(HttpServletRequest request);
@Operation(summary = "Api to validate call",

View File

@@ -65,8 +65,8 @@ public class CallApiController implements CallApi {
@Override
@Transactional(readOnly = true)
public ResponseEntity<Response<List<CallDetailsResponseBean>>> getAllCalls() {
List<CallDetailsResponseBean> calls = callService.getAllCalls();
public ResponseEntity<Response<List<CallDetailsResponseBean>>> getAllCalls(HttpServletRequest request) {
List<CallDetailsResponseBean> calls = callService.getAllCalls(request);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(calls, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG)));

View File

@@ -633,6 +633,24 @@
<column name="final_form" type="INTEGER"></column>
</addColumn>
</changeSet>
<changeSet id="13-09-2024_1" author="Harish Bagora">
<addColumn tableName="form_field">
<column name="description" type="TEXT">
<constraints nullable="true"/>
</column>
<column name="sort_order" type="INTEGER">
<constraints nullable="true"/>
</column>
</addColumn>
</changeSet>
<changeSet id="13-09-2024_2" author="Harish Bagora">
<sql>
TRUNCATE TABLE FORM_FIELD RESTART IDENTITY;
</sql>
<sqlFile dbms="postgresql"
path="classpath:db/dump/inserted_form_field_data_13_09_2024.sql" />
</changeSet>
<changeSet id="12-09-2024_1" author="Rajesh Khore">
<addColumn tableName="flow_edges">

View File

@@ -0,0 +1,51 @@
INSERT INTO FORM_FIELD ( SORT_ORDER, NAME, LABEL, DESCRIPTION, SETTINGS, VALIDATORS, CREATED_DATE, UPDATED_DATE)
VALUES
( 1, 'textinput', 'Testo Breve', 'Per risposte concise (nomi, titoli, brevi descrizioni)',
'{"label": "Testo Breve", "placeholder": ""}',
'{"isRequired": false, "minLength": null, "maxLength": null, "pattern": null, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 2, 'textarea', 'Testo Lungo', 'Campo di testo esteso per paragrafi, descrizioni, proposte',
'{"label": "Testo Lungo", "placeholder": ""}',
'{"isRequired": false, "minLength": null, "maxLength": null, "pattern": null, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 3, 'wysiwyg', 'Campo di Testo Formattato', 'Editor avanzato per testo con formattazione',
'{"label": "Testo Formattato", "placeholder": ""}',
'{"isRequired": false, "minLength": null, "maxLength": null, "pattern": null, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 4, 'numberinput', 'Campo Numerico', 'Per l''inserimento di valori numerici (quantità, importi, percentuali)',
'{"label": "Numero", "placeholder": "0", "step": "0"}',
'{"isRequired": false, "min": null, "max": null, "pattern": null, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
(5, 'radio', 'Scelta Singola', 'Gruppo di opzioni per selezione singola',
'{"label": "Scelta Singola", "options": []}',
'{"isRequired": false, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 6, 'select', 'Menu a Tendina', 'Selezione da opzioni predefinite',
'{"label": "Menu a Tendina", "options": []}',
'{"isRequired": false, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 7, 'checkboxes', 'Scelta Multipla', 'Gruppo di opzioni per selezione singola o multipla',
'{"label": "Scelta Multipla", "options": []}',
'{"isRequired": false, "min": null, "max": null, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 8, 'switch', 'Casella di Spunta', 'Per selezioni binarie, accettazioni, conferme',
'{"label": "Casella di Spunta"}',
'{"isRequired": false}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 9, 'datepicker', 'Data', 'Selezione di data',
'{"label": "Data"}',
'{"isRequired": false, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
( 10, 'fileupload', 'Caricamento File', 'Per l''upload di documenti o immagini',
'{"label": "Caricamento File", "mime": []}',
'{"isRequired": false, "maxSize": 100000, "custom": null}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

View File

@@ -139,3 +139,4 @@ flow.created.successfully=Flow created successfully.
flow.fetched.successfully=Flow fetched successfully.
flow.already.exists= Flow already exist for this call.
flow.request.not.complete=Flow request is not complete.
flow.not.found=Flow not found.

View File

@@ -56,7 +56,7 @@ status.same.error=Lo stato <20> gi<67> impostato.
invalid.status.change.from.draft=Lo stato non pu<70> essere cambiato in READY_TO_PUBLISH o PUBLISH da DRAFT.
status.cannot.be.changed=Lo stato non pu<70> essere cambiato.
published.call.not.update=Il bando pubblicato non pu<70> essere aggiornato.
invalid.status.change.from.publish=Lo stato non può essere modificato in READY_TO_PUBLISH o DRAFT da PUBLISH.
invalid.status.change.from.publish=Lo stato non pu<EFBFBD> essere modificato in READY_TO_PUBLISH o DRAFT da PUBLISH.
# Login-related messages
@@ -115,7 +115,7 @@ lookupdata.created.successfully=LookUpData creato correttamente.
lookupdata.fetched.successfully=LookUpData recuperato correttamente.
lookupdata.updated.successfully=LookUpData aggiornato correttamente.
lookupdata.deleted.successfully=LookUpData eliminato correttamente.
lookupdata.value.cannot.be.empty=Il campo valore non può essere vuoto
lookupdata.value.cannot.be.empty=Il campo valore non pu<EFBFBD> essere vuoto
#Document-related message
document.updated.successfully=Documento aggiornato con successo.
@@ -133,5 +133,6 @@ update.user.status.success=Lo stato dell'utente <20> stato aggiornato con success
#Flow-related message
flow.created.successfully=Flusso creato con successo.
flow.fetched.successfully=Flusso recuperato con successo.
flow.already.exists= Il flusso esiste già per questa chiamata.
flow.request.not.complete=La richiesta di flusso non è completa.
flow.already.exists= Il flusso esiste gi<EFBFBD> per questa chiamata.
flow.request.not.complete=La richiesta di flusso non <EFBFBD> completa.
flow.not.found=Flow not found.