FINERACT-2218: Fix Type Mismatch in Survey Validation Query

This commit is contained in:
Pinchez25
2025-08-07 10:21:55 +02:00
committed by Adam Saghy
parent 0601bfca77
commit 52d3f32381
5 changed files with 411 additions and 96 deletions
@@ -18,6 +18,18 @@
*/
package org.apache.fineract.spm.data;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* Model representing a survey response option for internal mapping
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class ResponseData {
private Long id;
@@ -25,43 +37,4 @@ public class ResponseData {
private Integer value;
private Integer sequenceNo;
public ResponseData() {
}
public ResponseData(final Long id, final String text, final Integer value, final Integer sequenceNo) {
this.id = id;
this.text = text;
this.value = value;
this.sequenceNo = sequenceNo;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public Integer getSequenceNo() {
return sequenceNo;
}
public void setSequenceNo(Integer sequenceNo) {
this.sequenceNo = sequenceNo;
}
}
@@ -18,7 +18,7 @@
*/
package org.apache.fineract.spm.domain;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@@ -27,11 +27,11 @@ import org.springframework.data.repository.query.Param;
public interface SurveyRepository extends JpaRepository<Survey, Long> {
@Query("select s from Survey s where :pointInTime between s.validFrom and s.validTo")
List<Survey> fetchActiveSurveys(@Param("pointInTime") LocalDateTime pointInTime);
List<Survey> fetchActiveSurveys(@Param("pointInTime") LocalDate pointInTime);
@Query("select s from Survey s ")
List<Survey> fetchAllSurveys();
@Query("select s from Survey s where s.key = :key and :pointInTime between s.validFrom and s.validTo")
Survey findByKey(@Param("key") String key, @Param("pointInTime") LocalDateTime pointInTime);
Survey findByKey(@Param("key") String key, @Param("pointInTime") LocalDate pointInTime);
}
@@ -44,7 +44,7 @@ public class SpmService {
public List<Survey> fetchValidSurveys() {
this.securityContext.authenticatedUser();
return this.surveyRepository.fetchActiveSurveys(DateUtils.getLocalDateTimeOfSystem());
return this.surveyRepository.fetchActiveSurveys(DateUtils.getLocalDateOfTenant());
}
public List<Survey> fetchAllSurveys() {
@@ -61,7 +61,7 @@ public class SpmService {
public Survey createSurvey(final Survey survey) {
this.securityContext.authenticatedUser();
this.surveyValidator.validate(survey);
final Survey previousSurvey = this.surveyRepository.findByKey(survey.getKey(), DateUtils.getLocalDateTimeOfSystem());
final Survey previousSurvey = this.surveyRepository.findByKey(survey.getKey(), DateUtils.getLocalDateOfTenant());
if (previousSurvey != null) {
this.deactivateSurvey(previousSurvey.getId());
@@ -18,31 +18,201 @@
*/
package org.apache.fineract.integrationtests;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.LocalDate;
import java.util.List;
import org.apache.fineract.client.models.SurveyData;
import org.apache.fineract.integrationtests.client.IntegrationTest;
import org.apache.fineract.integrationtests.common.SurveyHelper;
import org.apache.fineract.integrationtests.common.Utils;
import org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Loan Integration Test for checking Loan Application Repayment Schedule.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SurveyIntegrationTest {
public class SurveyIntegrationTest extends IntegrationTest {
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private LoanTransactionHelper loanTransactionHelper;
private static final Logger LOG = LoggerFactory.getLogger(SurveyIntegrationTest.class);
private static final int SURVEY_VALIDITY_YEARS = 100;
private static final String TEST_SURVEY_PREFIX = "Test Survey ";
private static final String KENYAN_COUNTRY_CODE = "KE";
private static final String DEFAULT_DESCRIPTION = "Test Survey Description";
private static final List<String> BASIC_QUESTIONS = List.of("Question 1", "Question 2");
private static final List<String> DEFAULT_VALIDITY_QUESTIONS = List.of("Default Question 1", "Default Question 2",
"Default Question 3");
private static final List<String> MULTIPLE_QUESTIONS = List.of("What is your age?", "What is your occupation?",
"What is your income level?", "Do you own a house?", "How many children do you have?", "What is your education level?",
"Do you have a bank account?", "What is your marital status?");
private SurveyHelper surveyHelper;
@BeforeEach
public void setup() {
void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
this.surveyHelper = new SurveyHelper(fineractClient());
}
@Test
@Order(1)
void testCreateSurvey() {
LOG.info("Creating Survey");
final String surveyName = generateSurveyName();
final LocalDate validFrom = Utils.getLocalDateOfTenant();
final LocalDate validTo = validFrom.plusYears(SURVEY_VALIDITY_YEARS);
surveyHelper.createSurvey(surveyName, DEFAULT_DESCRIPTION, validFrom, validTo, BASIC_QUESTIONS);
LOG.info("Survey created: {}", surveyName);
}
@Test
@Order(2)
void testCreateSurveyWithDefaultValidity() {
LOG.info("Creating Survey with Default Validity");
final String surveyName = generateSurveyName();
final String description = "Test Survey with Default Validity";
surveyHelper.createSurvey(surveyName, description, DEFAULT_VALIDITY_QUESTIONS);
LOG.info("Survey created with default validity: {}", surveyName);
}
@Test
@Order(3)
void testCreateSurveyWithInvalidData() {
LOG.info("Testing Survey Creation with Invalid Data");
final String surveyName = generateSurveyName();
final LocalDate validFrom = Utils.getLocalDateOfTenant();
final LocalDate validTo = validFrom.plusYears(SURVEY_VALIDITY_YEARS);
final List<String> emptyQuestions = List.of();
final Exception exception = assertThrows(RuntimeException.class,
() -> surveyHelper.createSurvey(surveyName, DEFAULT_DESCRIPTION, validFrom, validTo, emptyQuestions));
assertThat(exception.getMessage()).containsIgnoringCase("question");
}
@Test
@Order(4)
void testRetrieveActiveSurveys() {
LOG.info("Testing Retrieve Active Surveys");
final String surveyName = createTestSurvey("Test Survey for Retrieval", List.of("Retrieval Question 1", "Retrieval Question 2"));
List<SurveyData> activeSurveys = surveyHelper.retrieveActiveSurveys();
assertThat(activeSurveys).isNotNull();
assertThat(activeSurveys).hasSizeGreaterThanOrEqualTo(1);
verifyCreatedSurveyExists(activeSurveys, surveyName);
LOG.info("Retrieved {} active surveys", activeSurveys.size());
}
@Test
@Order(5)
void testSurveyProperties() {
LOG.info("Testing Survey Properties");
final String surveyName = generateSurveyName();
final String description = "Test Survey for Properties";
final LocalDate validFrom = Utils.getLocalDateOfTenant();
final LocalDate validTo = validFrom.plusYears(SURVEY_VALIDITY_YEARS);
final List<String> questions = List.of("Property Question 1", "Property Question 2", "Property Question 3");
surveyHelper.createSurvey(surveyName, description, validFrom, validTo, questions);
SurveyData createdSurvey = findSurveyByName(surveyName);
verifySurveyProperties(createdSurvey, surveyName, description, validFrom, validTo, 3);
LOG.info("Survey properties verified successfully");
}
@Test
@Order(6)
void testCreateSurveyWithMultipleQuestions() {
LOG.info("Testing Survey Creation with Multiple Questions");
final String surveyName = createTestSurvey("Test Survey with Multiple Questions", MULTIPLE_QUESTIONS);
SurveyData createdSurvey = findSurveyByName(surveyName);
assertThat(surveyHelper.getSurveyQuestionsCount(createdSurvey)).isEqualTo(MULTIPLE_QUESTIONS.size());
LOG.info("Survey created with {} questions successfully", MULTIPLE_QUESTIONS.size());
}
@Test
@Order(7)
void testCreateSurveyWithSpecialCharacters() {
LOG.info("Testing Survey Creation with Special Characters");
final String surveyName = "Test Survey with Special Chars: @#$%^&*()_+-=[]{}|;':\",./<>?";
final String description = "Test Survey Description with special characters: £€¥¢₦₹₿";
final List<String> questions = List.of("Question with special chars: @#$%^&*()", "Another question with £€¥ symbols");
surveyHelper.createSurvey(surveyName, description, questions);
LOG.info("Survey created with special characters successfully");
}
@Test
@Order(8)
void testCreateSurveyWithLongText() {
LOG.info("Testing Survey Creation with Long Text");
final String surveyName = generateSurveyName();
final String description = buildLongDescription();
final List<String> questions = List.of(buildLongQuestion("first test case"), buildLongQuestion("second test scenario"));
surveyHelper.createSurvey(surveyName, description, questions);
LOG.info("Survey created with long text successfully");
}
private String generateSurveyName() {
return TEST_SURVEY_PREFIX + System.currentTimeMillis();
}
private String createTestSurvey(String description, List<String> questions) {
final String surveyName = generateSurveyName();
surveyHelper.createSurvey(surveyName, description, questions);
return surveyName;
}
private SurveyData findSurveyByName(String surveyName) {
List<SurveyData> activeSurveys = surveyHelper.retrieveActiveSurveys();
return activeSurveys.stream().filter(survey -> surveyName.equals(survey.getName())).findFirst()
.orElseThrow(() -> new RuntimeException("Created survey not found: " + surveyName));
}
private void verifyCreatedSurveyExists(List<SurveyData> surveys, String surveyName) {
boolean foundSurvey = surveys.stream().anyMatch(survey -> surveyName.equals(survey.getName()));
assertThat(foundSurvey).isTrue();
}
private void verifySurveyProperties(SurveyData survey, String expectedName, String expectedDescription, LocalDate expectedValidFrom,
LocalDate expectedValidTo, int expectedQuestionCount) {
assertThat(surveyHelper.getSurveyName(survey)).isEqualTo(expectedName);
assertThat(surveyHelper.getSurveyDescription(survey)).isEqualTo(expectedDescription);
assertThat(surveyHelper.getSurveyValidFrom(survey)).isEqualTo(expectedValidFrom);
assertThat(surveyHelper.getSurveyValidTo(survey)).isEqualTo(expectedValidTo);
assertThat(surveyHelper.getSurveyQuestionsCount(survey)).isEqualTo(expectedQuestionCount);
assertThat(surveyHelper.getSurveyCountryCode(survey)).isEqualTo(KENYAN_COUNTRY_CODE);
assertThat(surveyHelper.getSurveyKey(survey)).isNotNull();
}
private String buildLongDescription() {
return "This is a very long description for testing purposes. "
+ "It contains multiple sentences to ensure that the system can handle longer text inputs "
+ "without any issues. The description should be properly stored and retrieved without "
+ "any truncation or encoding problems.";
}
private String buildLongQuestion(String testCaseDescription) {
return "This is a very long question that tests the system's ability to handle longer text inputs "
+ "without any issues. The question should be properly stored and retrieved for " + testCaseDescription + ".";
}
}
@@ -18,48 +18,225 @@
*/
package org.apache.fineract.integrationtests.common;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.gson.Gson;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import java.util.HashMap;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.apache.fineract.client.models.QuestionData;
import org.apache.fineract.client.models.ResponseData;
import org.apache.fineract.client.models.SurveyData;
import org.apache.fineract.client.services.SpmSurveysApi;
import org.apache.fineract.client.util.FineractClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Call;
import retrofit2.Response;
public final class SurveyHelper {
private SurveyHelper() {
}
public class SurveyHelper {
private static final Logger LOG = LoggerFactory.getLogger(SurveyHelper.class);
private static final String FULFIL_SURVEY_URL = "/fineract-provider/api/v1/survey/ppi_kenya_2009/clientId?" + Utils.TENANT_IDENTIFIER;
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final int DEFAULT_VALIDITY_YEARS = 100;
private static final String SURVEY_KEY_PREFIX = "SURVEY_";
private static final String QUESTION_KEY_PREFIX = "Q";
private static final String QUESTION_DESC_PREFIX = "Question ";
private static final String YES_RESPONSE = "Yes";
private static final String NO_RESPONSE = "No";
private static final String ACTIVATE_COMMAND = "activate";
private static final String DEACTIVATE_COMMAND = "deactivate";
private final SpmSurveysApi surveysApi;
public SurveyHelper(final FineractClient fineractClient) {
this.surveysApi = fineractClient.surveys;
}
public Long createSurvey(String name, String description, LocalDate validFrom, LocalDate validTo, List<String> questions) {
validateSurveyInputs(name, description, questions);
try {
SurveyData surveyData = buildSurveyData(name, description, validFrom, validTo, questions);
return executeSurveyCreation(surveyData, name);
} catch (Exception e) {
LOG.error("Exception whilst creating survey: {}", e.getMessage(), e);
throw new RuntimeException("Failed to create survey: " + e.getMessage(), e);
}
}
public Long createSurvey(String name, String description, List<String> questions) {
LocalDate validFrom = Utils.getLocalDateOfTenant();
LocalDate validTo = validFrom.plusYears(DEFAULT_VALIDITY_YEARS);
return createSurvey(name, description, validFrom, validTo, questions);
}
public SurveyData retrieveSurvey(Long surveyId) {
return executeApiCall(() -> surveysApi.findSurvey(surveyId), "Failed to retrieve survey with ID: " + surveyId);
}
public List<SurveyData> retrieveAllSurveys() {
return executeApiCall(() -> surveysApi.fetchAllSurveys1(null), "Failed to retrieve all surveys");
}
public List<SurveyData> retrieveActiveSurveys() {
return executeApiCall(() -> surveysApi.fetchAllSurveys1(true), "Failed to retrieve active surveys");
}
public String updateSurvey(Long surveyId, SurveyData surveyData) {
String result = executeApiCall(() -> surveysApi.editSurvey(surveyId, surveyData), "Failed to update survey with ID: " + surveyId);
LOG.info("Survey updated successfully: {}", surveyId);
return result;
}
public void deactivateSurvey(Long surveyId) {
changeSurveyStatus(surveyId, DEACTIVATE_COMMAND, "deactivated");
}
public void activateSurvey(Long surveyId) {
changeSurveyStatus(surveyId, ACTIVATE_COMMAND, "activated");
}
public String getSurveyName(SurveyData survey) {
return survey.getName();
}
public String getSurveyDescription(SurveyData survey) {
return survey.getDescription();
}
public LocalDate getSurveyValidFrom(SurveyData survey) {
return survey.getValidFrom();
}
public LocalDate getSurveyValidTo(SurveyData survey) {
return survey.getValidTo();
}
public int getSurveyQuestionsCount(SurveyData survey) {
return survey.getQuestionDatas() != null ? survey.getQuestionDatas().size() : 0;
}
public String getSurveyKey(SurveyData survey) {
return survey.getKey();
}
public String getSurveyCountryCode(SurveyData survey) {
return survey.getCountryCode();
}
private void validateSurveyInputs(String name, String description, List<String> questions) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Survey name cannot be null or empty");
}
if (questions == null || questions.isEmpty()) {
throw new IllegalArgumentException("Survey must have at least one question");
}
}
private SurveyData buildSurveyData(String name, String description, LocalDate validFrom, LocalDate validTo, List<String> questions) {
SurveyData surveyData = new SurveyData().name(name).description(description).validFrom(validFrom).validTo(validTo).countryCode("KE")
.key(SURVEY_KEY_PREFIX + System.currentTimeMillis());
surveyData.questionDatas(buildQuestionDataList(questions));
return surveyData;
}
private List<QuestionData> buildQuestionDataList(List<String> questions) {
List<QuestionData> questionDataList = new ArrayList<>(questions.size());
for (int i = 0; i < questions.size(); i++) {
QuestionData questionData = new QuestionData().text(questions.get(i)).sequenceNo(i + 1).key(QUESTION_KEY_PREFIX + (i + 1))
.description(QUESTION_DESC_PREFIX + (i + 1)).responseDatas(createYesNoResponses());
questionDataList.add(questionData);
}
return questionDataList;
}
private List<ResponseData> createYesNoResponses() {
List<ResponseData> responses = new ArrayList<>(2);
responses.add(new ResponseData().text(YES_RESPONSE).value(1).sequenceNo(1));
responses.add(new ResponseData().text(NO_RESPONSE).value(0).sequenceNo(2));
return responses;
}
private Long executeSurveyCreation(SurveyData surveyData, String surveyName) throws Exception {
Call<Void> call = surveysApi.createSurvey(surveyData);
Response<Void> response = call.execute();
if (response.isSuccessful()) {
LOG.info("Survey created successfully: {}", surveyName);
return null;
} else {
String errorBody = getErrorBody(response);
LOG.error("Failed to create survey: {}", errorBody);
throw new RuntimeException("Failed to create survey: " + errorBody);
}
}
private void changeSurveyStatus(Long surveyId, String command, String action) {
executeVoidApiCall(() -> surveysApi.activateOrDeactivateSurvey(surveyId, command),
"Failed to " + action.toLowerCase() + " survey with ID: " + surveyId);
LOG.info("Survey {} successfully: {}", action, surveyId);
}
private <T> T executeApiCall(ApiCallSupplier<T> apiCall, String errorMessage) {
try {
Response<T> response = apiCall.get().execute();
if (response.isSuccessful()) {
return response.body();
} else {
String errorBody = getErrorBody(response);
throw new RuntimeException(errorMessage + ": " + errorBody);
}
} catch (Exception e) {
throw new RuntimeException(errorMessage + ": " + e.getMessage(), e);
}
}
private void executeVoidApiCall(ApiCallSupplier<Void> apiCall, String errorMessage) {
try {
Response<Void> response = apiCall.get().execute();
if (!response.isSuccessful()) {
String errorBody = getErrorBody(response);
throw new RuntimeException(errorMessage + ": " + errorBody);
}
} catch (Exception e) {
throw new RuntimeException(errorMessage + ": " + e.getMessage(), e);
}
}
private String getErrorBody(Response<?> response) {
try {
return response.errorBody() != null ? response.errorBody().string() : "Unknown error";
} catch (Exception e) {
return "Error reading response body: " + e.getMessage();
}
}
@FunctionalInterface
private interface ApiCallSupplier<T> {
Call<T> get() throws Exception;
}
// TODO: Rewrite to use fineract-client instead!
// Example: org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper.disburseLoan(java.lang.Long,
// org.apache.fineract.client.models.PostLoansLoanIdRequest)
@Deprecated(forRemoval = true)
public static Integer fulfilSurvey(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) {
public static Integer fulfilSurvey(final io.restassured.specification.RequestSpecification requestSpec,
final io.restassured.specification.ResponseSpecification responseSpec) {
return fulfilSurvey(requestSpec, responseSpec, "04 March 2011");
}
// TODO: Rewrite to use fineract-client instead!
// Example: org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper.disburseLoan(java.lang.Long,
// org.apache.fineract.client.models.PostLoansLoanIdRequest)
@Deprecated(forRemoval = true)
public static Integer fulfilSurvey(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final String activationDate) {
public static Integer fulfilSurvey(final io.restassured.specification.RequestSpecification requestSpec,
final io.restassured.specification.ResponseSpecification responseSpec, final String activationDate) {
LOG.info("---------------------------------FULFIL PPI ---------------------------------------------");
final String FULFIL_SURVEY_URL = "/fineract-provider/api/v1/survey/ppi_kenya_2009/clientId?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(requestSpec, responseSpec, FULFIL_SURVEY_URL, getTestPPIAsJSON(), "clientId");
}
// TODO: Rewrite to use fineract-client instead!
// Example: org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper.disburseLoan(java.lang.Long,
// org.apache.fineract.client.models.PostLoansLoanIdRequest)
@Deprecated(forRemoval = true)
public static String getTestPPIAsJSON() {
final HashMap<String, String> map = new HashMap<>();
final java.util.HashMap<String, String> map = new java.util.HashMap<>();
map.put("date", "2014-05-19 00:00:00");
map.put("ppi_household_members_cd_q1_householdmembers", "107");
@@ -68,7 +245,6 @@ public final class SurveyHelper {
map.put("dateFormat", "dd MMMM yyyy");
map.put("locale", "en");
map.put("ppi_habitablerooms_cd_q4_habitablerooms", "120");
map.put("ppi_floortype_cd_q5_floortype", "124");
map.put("ppi_lightingsource_cd_q6_lightingsource", "126");
map.put("ppi_irons_cd_q7_irons", "128");
@@ -77,20 +253,16 @@ public final class SurveyHelper {
map.put("ppi_fryingpans_cd_q10_fryingpans", "138");
LOG.info("map : {}", map);
return new Gson().toJson(map);
return new com.google.gson.Gson().toJson(map);
}
// TODO: Rewrite to use fineract-client instead!
// Example: org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper.disburseLoan(java.lang.Long,
// org.apache.fineract.client.models.PostLoansLoanIdRequest)
@Deprecated(forRemoval = true)
public static void verifySurveyCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final Integer generatedClientID) {
public static void verifySurveyCreatedOnServer(final io.restassured.specification.RequestSpecification requestSpec,
final io.restassured.specification.ResponseSpecification responseSpec, final Integer generatedClientID) {
LOG.info("------------------------------CHECK CLIENT DETAILS------------------------------------\n");
final String SURVEY_URL = "/fineract-provider/api/v1/Survey/ppi_kenya_2009/clientid/entryId" + generatedClientID + "?"
+ Utils.TENANT_IDENTIFIER;
final Integer responseClientID = Utils.performServerGet(requestSpec, responseSpec, SURVEY_URL, "id");
assertEquals(generatedClientID, responseClientID, "ERROR IN CREATING THE CLIENT");
org.junit.jupiter.api.Assertions.assertEquals(generatedClientID, responseClientID, "ERROR IN CREATING THE CLIENT");
}
}