From 59429326d12fe853a5e15c506bb97d0a95c9b8d8 Mon Sep 17 00:00:00 2001 From: CieyouRaoul Date: Fri, 7 Mar 2014 13:13:49 +0100 Subject: [PATCH 1/4] PPI implementation ppi step 2 work in progress wip work in progress wip ppi permission done --- api-docs/apiLive.htm | 338 +++++++++++++++++- .../V148__x_registered_table_category.sql | 1 + .../V149__addScrore_Column_to_code_value.sql | 2 + .../core_db/V150__ppi_permision.sql | 3 + .../commands/domain/CommandWrapper.java | 24 ++ .../service/CommandWrapperBuilder.java | 41 +++ .../SynchronousCommandProcessingService.java | 33 +- .../api/GlobalConfigurationApiResource.java | 11 +- .../domain/GlobalConfigurationProperty.java | 5 + .../ConfigurationReadPlatformService.java | 7 +- .../ConfigurationReadPlatformServiceImpl.java | 16 +- ...obalConfigurationWritePlatformService.java | 2 + ...WritePlatformServiceJpaRepositoryImpl.java | 41 +++ .../dataqueries/api/DataTableApiConstant.java | 21 ++ .../api/DatatablesApiResource.java | 17 +- .../dataqueries/data/DataTableValidator.java | 51 +++ .../dataqueries/data/DatatableData.java | 2 + .../data/ResultsetColumnValueData.java | 7 + .../RegisterDatatableCommandHandler.java | 35 ++ .../service/GenericDataServiceImpl.java | 17 +- .../service/ReadWriteNonCoreDataService.java | 16 +- .../ReadWriteNonCoreDataServiceImpl.java | 271 ++++++++++++-- .../survey/api/LikelihoodApiConstants.java | 25 ++ .../survey/api/LikelihoodApiResource.java | 95 +++++ .../survey/api/PovertyLineApiConstants.java | 12 + .../survey/api/PovertyLineApiResource.java | 82 +++++ .../survey/api/SurveyApiConstants.java | 10 + .../survey/api/SurveyApiResource.java | 179 ++++++++++ .../survey/data/ClientScoresOverview.java | 32 ++ .../data/LikeliHoodPovertyLineData.java | 38 ++ .../survey/data/LikelihoodData.java | 27 ++ .../survey/data/LikelihoodDataValidator.java | 55 +++ .../survey/data/LikelihoodStatus.java | 10 + .../survey/data/PovertyLineData.java | 23 ++ .../survey/data/PpiPovertyLineData.java | 23 ++ .../survey/data/SurveyData.java | 7 + .../survey/data/SurveyDataTableData.java | 30 ++ .../survey/domain/Likelihood.java | 68 ++++ .../survey/domain/LikelihoodRepository.java | 15 + .../handler/FullFilSurveyCommandHandler.java | 32 ++ .../handler/RegisterSurveyCommandHandler.java | 33 ++ .../UpdateLikelihoodCommandHandler.java | 32 ++ .../survey/service/PovertyLineService.java | 19 + .../service/PovertyLineServiceImpl.java | 165 +++++++++ .../survey/service/ReadLikelihoodService.java | 14 + .../service/ReadLikelihoodServiceImpl.java | 98 +++++ .../survey/service/ReadSurveyService.java | 25 ++ .../survey/service/ReadSurveyServiceImpl.java | 162 +++++++++ .../service/WriteLikelihoodService.java | 12 + .../service/WriteLikelihoodServiceImpl.java | 103 ++++++ .../survey/service/WriteSurveyService.java | 14 + .../service/WriteSurveyServiceImpl.java | 139 +++++++ 52 files changed, 2480 insertions(+), 60 deletions(-) create mode 100644 mifosng-db/migrations/core_db/V148__x_registered_table_category.sql create mode 100644 mifosng-db/migrations/core_db/V149__addScrore_Column_to_code_value.sql create mode 100644 mifosng-db/migrations/core_db/V150__ppi_permision.sql create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DataTableApiConstant.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DataTableValidator.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiConstants.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiConstants.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiResource.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiConstants.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikeliHoodPovertyLineData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodDataValidator.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodStatus.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PovertyLineData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PpiPovertyLineData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyDataTableData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/FullFilSurveyCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/RegisterSurveyCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineServiceImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodServiceImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyServiceImpl.java diff --git a/api-docs/apiLive.htm b/api-docs/apiLive.htm index db355742c..a602a8078 100644 --- a/api-docs/apiLive.htm +++ b/api-docs/apiLive.htm @@ -1409,11 +1409,37 @@ AdHoc Search search/advance - Advance Search + Advance Search + + Survey + survey/ + + List surveys + + + + + + survey/{surveyName} + + Retreivesurvey details + + + + + + survey/{surveyName}/{clientId} + Create Entry in the survey table + + + + + + @@ -10268,6 +10294,39 @@ GET https://DomainName/api/v1/configurations +   +
+
+

Retrieve Global Configuration for surveys

+

Returns the list global enable/disable survey configurations.

+

Example Requests:

+
configurations/survey
+
+
+ + GET https://DomainName/api/v1/configurations/survey + + + { + "ppi_kenya_2005": [ + { + "name": "maker-checker", + "enabled": true, + "value": 0, + "id": 1 + }, + { + "name": "ppi_tanzania_20012", + "enabled": false, + "value": 0, + "id": 2 + }, + ] + } + +
+
+  
@@ -17373,7 +17432,10 @@ No Request Body

Register Data Table

Registers a data table with the Mifos X Core application table. This allows the data table to be maintained through the - API.

+ API. + In case the datatable is a PPI (survey table)a parameter category should be pass along with the request. + The API currently support one category (200) +

@@ -17384,7 +17446,10 @@ POST datatables/register/extra_client_details/m_client Content-Type: application/json Request Body: -{} +{ + category:200 + locale:"en_GB" +} { @@ -17738,7 +17803,262 @@ Request Body:
- + + + +   +
+
+

Retreive surveys

+

Retrieve surveys. This allows to retrieve the list of survey tables registered . +

+
+
+ + GET https://DomainName/api/v1/survey/ + + + GET survey/ + + Content-Type: application/json + Request Body: + {} + + + [ + { + "datatableData": { + "applicationTableName": "m_client", + "registeredTableName": "ppi_kenya_2005", + "columnHeaderData": [ + { + "columnName": "id", + "columnType": "bigint", + "columnLength": 0, + "columnDisplayType": "INTEGER", + "isColumnNullable": false, + "isColumnPrimaryKey": true, + "columnValues": [] + }, + { + "columnName": "client_id", + "columnType": "int", + "columnLength": 0, + "columnDisplayType": "INTEGER", + "isColumnNullable": false, + "isColumnPrimaryKey": false, + "columnValues": [] + }, + { + "columnName": "ppi_household_members_cd_q1_householdmembers", + "columnType": "int", + "columnLength": 0, + "columnDisplayType": "CODELOOKUP", + "isColumnNullable": false, + "isColumnPrimaryKey": false, + "columnValues": [ + { + "id": 167, + "value": "Nine or More", + "score": 0 + }, + { + "id": 168, + "value": "Seven or eight", + "score": 5 + }, + { + "id": 169, + "value": "Six", + "score": 8 + }, + + ], + "columnCode": "ppi_household_members" + }, + { + "columnName": "date", + "columnType": "datetime", + "columnLength": 0, + "columnDisplayType": "DATETIME", + "isColumnNullable": false, + "isColumnPrimaryKey": false, + "columnValues": [] + } + ] + }, + "enabled": false + }, + { + "datatableData": { + "applicationTableName": "m_client", + "registeredTableName": "ppi_tanzania_20012", + "columnHeaderData": [ + { + "columnName": "id", + "columnType": "bigint", + "columnLength": 0, + "columnDisplayType": "INTEGER", + "isColumnNullable": false, + "isColumnPrimaryKey": true, + "columnValues": [] + }, + { + "columnName": "client_id", + "columnType": "int", + "columnLength": 0, + "columnDisplayType": "INTEGER", + "isColumnNullable": false, + "isColumnPrimaryKey": false, + "columnValues": [] + }, + { + "columnName": "ppi_youngerthan17_cd_q1_youngerthan17", + "columnType": "int", + "columnLength": 0, + "columnDisplayType": "CODELOOKUP", + "isColumnNullable": false, + "isColumnPrimaryKey": false, + "columnValues": [ + { + "id": 204, + "value": "four or More", + "score": 0 + }, + + ], + "columnCode": "ppi_youngerthan17" + }, + ], + "columnCode": "ppi_how_many_tables" + }, + ] + }, + "enabled": true + } + ] + +
+
+ + +   +
+
+

Retreive survey

+

Lists a registered survey table details and the Mifos X Core application table they are registered to. +

+
+
+ + GET https://DomainName/api/v1/survey/ppi_kenya_2005 + + + GET survey/{surveyName} + + Content-Type: application/json + Request Body: + {} + + + { + "applicationTableName": "m_client", + "registeredTableName": "extra_client_details", + "columnHeaderData": [ + { + "columnName": "client_id", + "columnType": "bigint", + "columnLength": 0, + "columnDisplayType": "INTEGER", + "isColumnNullable": false, + "isColumnPrimaryKey": true, + "columnValues": [] + }, + { + "columnName": "Gender_cd_Question", + "columnType": "int", + "columnLength": 0, + "columnDisplayType": "INTEGER", + "isColumnNullable": true, + "isColumnPrimaryKey": false, + "columnValues": [] + }, + { + "columnName": "Some Decimal", + "columnType": "decimal", + "columnLength": 0, + "columnDisplayType": "DECIMAL", + "isColumnNullable": true, + "isColumnPrimaryKey": false, + "columnValues": [] + }, + { + "columnName": "Birth Date", + "columnType": "date", + "columnLength": 0, + "columnDisplayType": "DATE", + "isColumnNullable": true, + "isColumnPrimaryKey": false, + "columnValues": [] + } + enabled:false + ] + } + +
+
+ +   +
+
+

Create an entry in the survey table

+

Insert and entry in a survey table (full fill the survey). + +

+
+
+ + POST https://DomainName/api/v1/survey/ppi_kenya_2005/87 + + + POST survey/{surveyName}/{clientId} + + Content-Type: application/json + Request Body: + { + + ppi_household_members_cd_q1_householdmembers : 167, + ppi_highestschool_cd_q2_highestschool : 174 , + ppi_businessoccupation_cd_q3_businessoccupation : 180, + ppi_habitablerooms_cd_q4_habitablerooms :184, + ppi_floortype_cd_q5_floortype : 188, + ppi_lightingsource_cd_q6_lightingsource :190, + ppi_irons_cd_q7_irons:193, + ppi_mosquitonets_cd_q8_mosquitonets:195, + ppi_towels_cd_q9_towels:198, + ppi_fryingpans_cd_q10_fryingpans:201, + date:"2014-12-02 20:30:00", + dateFormat:"Y-m-d H:i:s", + locale:"en_GB" + + } + + + { + "officeId": 2, + "clientId": 87, + "resourceId": 87 + } + +
+
+ + + +  
@@ -22473,6 +22793,16 @@ No Request Body: Update Global Configuration + + + + + + Retrieve Surveys Global Configuration + + + + Codes codes diff --git a/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql b/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql new file mode 100644 index 000000000..88903f444 --- /dev/null +++ b/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql @@ -0,0 +1 @@ +ALTER TABLE `x_registered_table` ADD `category` INT NOT NULL ; \ No newline at end of file diff --git a/mifosng-db/migrations/core_db/V149__addScrore_Column_to_code_value.sql b/mifosng-db/migrations/core_db/V149__addScrore_Column_to_code_value.sql new file mode 100644 index 000000000..fabbec3a4 --- /dev/null +++ b/mifosng-db/migrations/core_db/V149__addScrore_Column_to_code_value.sql @@ -0,0 +1,2 @@ +ALTER TABLE `m_code_value` +ADD COLUMN `code_score` INT(11) NULL AFTER `order_position`; \ No newline at end of file diff --git a/mifosng-db/migrations/core_db/V150__ppi_permision.sql b/mifosng-db/migrations/core_db/V150__ppi_permision.sql new file mode 100644 index 000000000..b9a75a63f --- /dev/null +++ b/mifosng-db/migrations/core_db/V150__ppi_permision.sql @@ -0,0 +1,3 @@ +INSERT INTO `m_permission` (`id`, `grouping`, `code`, `entity_name`, `action_name`, `can_maker_checker`) VALUES (NULL, 'datatable', 'UPDATE_LIKELIHOOD', 'likelihood', 'UPDATE', '0'); + +INSERT INTO `m_permission` (`id`, `grouping`, `code`, `entity_name`, `action_name`, `can_maker_checker`) VALUES (NULL, 'survey', 'REGISTER_SURVEY', 'survey', 'CREATE', '0'); \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java index d9278f271..1c67fc64d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java @@ -123,6 +123,10 @@ public class CommandWrapper { public boolean isUpdateDatatable() { return this.actionName.equalsIgnoreCase("UPDATE") && this.href.startsWith("/datatables/") && this.entityId == null; } + public boolean isRegisterDatatable() { + return this.actionName.equalsIgnoreCase("REGISTER") && this.href.startsWith("/datatables/") && this.entityId == null; + } + public String getTaskPermissionName() { return this.taskPermissionName; @@ -683,4 +687,24 @@ public class CommandWrapper { public boolean isCacheResource() { return this.entityName.equalsIgnoreCase("CACHE"); } + + public boolean isLikelihoodResource() { + return this.entityName.equalsIgnoreCase("Likelihood"); + } + public boolean isSurveyResource() { + + return this.href.startsWith("/survey/"); + + } + public boolean isUpdateLikelihood() { + return this.actionName.equalsIgnoreCase("UPDATE"); + } + public boolean isRegisterSurvey() { + return this.actionName.equalsIgnoreCase("REGISTER"); + } + public boolean isFullFilSurvey() { + return this.actionName.equalsIgnoreCase("CREATE"); + } + + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java index bcac311f6..08a9ad596 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java @@ -500,6 +500,39 @@ public class CommandWrapperBuilder { } } + public CommandWrapperBuilder registerDBDatatable(final String datatable,final String apptable) + { + this.actionName = "REGISTER"; + this.entityName = "DATATABLE"; + this.entityId = null; + this.href = "/datatables/register/" + datatable+"/"+apptable; + + return this; + + } + + public CommandWrapperBuilder registerSurvey(final String datatable,final String apptable) + { + this.actionName = "REGISTER"; + this.entityName = "SURVEY"; + this.entityId = null; + this.href = "/survey/register/" + datatable+"/"+apptable; + + return this; + + } + + public CommandWrapperBuilder fullFilSurvey(final String datatable, final Long apptableId) { + + this.entityName =datatable; + this.entityId = apptableId; + this.actionName = "CREATE"; + + this.href = "/survey/" + datatable + "/" + apptableId; + + return this; + } + public CommandWrapperBuilder createLoanCharge(final Long loanId) { this.actionName = "CREATE"; this.entityName = "LOANCHARGE"; @@ -1510,4 +1543,12 @@ public class CommandWrapperBuilder { this.href = "/cache"; return this; } + + public CommandWrapperBuilder updateLikelihood(final Long entityId) { + this.actionName = "UPDATE"; + this.entityName = "LIKELIHOOD"; + this.href = "/likelihood/"+entityId; + this.entityId = entityId; + return this; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java index 4d4c20649..14716b37d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java @@ -7,6 +7,7 @@ package org.mifosplatform.commands.service; import java.util.Map; +import com.jcraft.jsch.Logger; import org.joda.time.DateTime; import org.mifosplatform.commands.domain.CommandSource; import org.mifosplatform.commands.domain.CommandSourceRepository; @@ -19,8 +20,10 @@ import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; +import org.mifosplatform.infrastructure.dataqueries.handler.RegisterDatatableCommandHandler; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.useradministration.domain.AppUser; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; @@ -34,6 +37,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer private final ToApiJsonSerializer> toApiJsonSerializer; private CommandSourceRepository commandSourceRepository; private final ConfigurationDomainService configurationDomainService; + private final static org.slf4j.Logger logger = LoggerFactory.getLogger(SynchronousCommandProcessingService.class); @Autowired public SynchronousCommandProcessingService(final PlatformSecurityContext context, final ApplicationContext applicationContext, @@ -57,6 +61,8 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer && !isApprovedByChecker; final NewCommandSourceHandler handler = findCommandHandler(wrapper); + + final CommandProcessingResult result = handler.processCommand(command); final AppUser maker = this.context.authenticatedUser(wrapper); @@ -130,7 +136,11 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer handler = this.applicationContext.getBean("deleteOneToManyDatatableEntryCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isDeleteOneToOne()) { handler = this.applicationContext.getBean("deleteOneToOneDatatableEntryCommandHandler", NewCommandSourceHandler.class); - } else { + }else if (wrapper.isRegisterDatatable()) { + + handler = this.applicationContext.getBean("registerDatatableCommandHandler", NewCommandSourceHandler.class); + } + else { throw new UnsupportedCommandException(wrapper.commandName()); } } else if (wrapper.isNoteResource()) { @@ -620,7 +630,26 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer throw new UnsupportedCommandException(wrapper.commandName()); } - } else { + + + }else if (wrapper.isLikelihoodResource()) { + if (wrapper.isUpdateLikelihood()) { + handler = this.applicationContext.getBean("updateLikelihoodCommandHandler", NewCommandSourceHandler.class); + } else { + throw new UnsupportedCommandException(wrapper.commandName()); + } + }else if (wrapper.isSurveyResource()) { + if (wrapper.isRegisterSurvey()) { + handler = this.applicationContext.getBean("registerSurveyCommandHandler", NewCommandSourceHandler.class); + } else if(wrapper.isFullFilSurvey()) + { + handler = this.applicationContext.getBean("fullFilSurveyCommandHandler", NewCommandSourceHandler.class); + } + else { + throw new UnsupportedCommandException(wrapper.commandName()); + } + } + else { throw new UnsupportedCommandException(wrapper.commandName()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java index 8aebf32d8..92a3e73c1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java @@ -9,12 +9,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; @@ -64,11 +59,11 @@ public class GlobalConfigurationApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveConfiguration(@Context final UriInfo uriInfo) { + public String retrieveConfiguration(@Context final UriInfo uriInfo,@DefaultValue("false") @QueryParam("survey") final boolean survey) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final GlobalConfigurationData configurationData = this.readPlatformService.retrieveGlobalConfiguration(); + final GlobalConfigurationData configurationData = this.readPlatformService.retrieveGlobalConfiguration(survey); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, configurationData, this.RESPONSE_DATA_PARAMETERS); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java index 2c235fc19..cb0b75b0b 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java @@ -76,4 +76,9 @@ public class GlobalConfigurationProperty extends AbstractPersistable { } + public static GlobalConfigurationProperty newSurveyConfiguration(final String name) + { + return new GlobalConfigurationProperty(name,false,null); + } + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java index 193feefef..b7da08c79 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java @@ -7,8 +7,13 @@ package org.mifosplatform.infrastructure.configuration.service; import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationData; +import java.util.List; + public interface ConfigurationReadPlatformService { - GlobalConfigurationData retrieveGlobalConfiguration(); + //GlobalConfigurationData retrieveGlobalConfiguration(); + GlobalConfigurationData retrieveGlobalConfiguration(boolean survey); + + // GlobalConfigurationData retrieveGlobalConfiguration(List configurationName); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java index 421d9637b..495f806eb 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java @@ -8,6 +8,7 @@ package org.mifosplatform.infrastructure.configuration.service; import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationData; import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationPropertyData; import org.mifosplatform.infrastructure.core.service.RoutingDataSource; +import org.mifosplatform.infrastructure.dataqueries.api.DataTableApiConstant; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; @@ -34,16 +35,27 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl } @Override - public GlobalConfigurationData retrieveGlobalConfiguration() { + public GlobalConfigurationData retrieveGlobalConfiguration(final boolean survey) { this.context.authenticatedUser(); - final String sql = "SELECT c.id, c.name, c.enabled, c.value FROM c_configuration c order by c.id"; + String sql = "SELECT c.id, c.name, c.enabled, c.value FROM c_configuration c "; + + if(survey) + { + sql += " JOIN x_registered_table on x_registered_table.registered_table_name = c.name "; + sql += " WHERE x_registered_table.category ="+DataTableApiConstant.CATEGORY_PPI; + + } + + sql += " order by c.id"; final List globalConfiguration = this.jdbcTemplate.query(sql, this.rm, new Object[] {}); return new GlobalConfigurationData(globalConfiguration); } + + private static final class GlobalConfigurationRowMapper implements RowMapper { @Override diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java index a14b99c77..fea85b3dd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java @@ -11,4 +11,6 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; public interface GlobalConfigurationWritePlatformService { CommandProcessingResult update(Long configId, JsonCommand command); + CommandProcessingResult update(String name, JsonCommand command); + void addSurveyConfig(String name); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java index f77c682f6..ad64270de 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java @@ -66,6 +66,47 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements } + @Transactional + @Override + public CommandProcessingResult update(final String name, final JsonCommand command) { + + this.context.authenticatedUser(); + + try { + this.globalConfigurationDataValidator.validateForUpdate(command); + + final GlobalConfigurationProperty configItemForUpdate = this.repository.findOneByNameWithNotFoundDetection(name); + + if (configItemForUpdate.updateTo(true)) { + this.repository.save(configItemForUpdate); + } + + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(configItemForUpdate.getId()).build(); + + } catch (final DataIntegrityViolationException dve) { + handleDataIntegrityIssues(dve); + return CommandProcessingResult.empty(); + } + + } + + @Transactional + @Override + public void addSurveyConfig(final String name) + { + try{ + final GlobalConfigurationProperty ppi = GlobalConfigurationProperty.newSurveyConfiguration(name); + this.repository.save(ppi); + } + catch (final DataIntegrityViolationException dve) + { + handleDataIntegrityIssues(dve); + } + + } + + + /* * Guaranteed to throw an exception no matter what the data integrity issue * is. diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DataTableApiConstant.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DataTableApiConstant.java new file mode 100644 index 000000000..7abcd71c4 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DataTableApiConstant.java @@ -0,0 +1,21 @@ +package org.mifosplatform.infrastructure.dataqueries.api; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by Cieyou on 2/26/14. + */ +public class DataTableApiConstant { + + public static final Integer CATEGORY_PPI = 200; + public static final Integer CATEGORY_DEFAULT = 100; + + public static final String categoryParamName ="category"; + public static final String localParamName = "locale"; + public static final Set REGISTER_PARAMS = new HashSet(Arrays.asList(categoryParamName,localParamName)); + + public static final String DATATABLE_RESOURCE_NAME ="dataTables"; + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java index 35ae92dc3..fe91a33e7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java @@ -6,6 +6,7 @@ package org.mifosplatform.infrastructure.dataqueries.api; import java.util.List; +import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -32,10 +33,14 @@ import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; import org.mifosplatform.infrastructure.dataqueries.service.GenericDataService; import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; +//import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + @Path("/datatables") @Component @Scope("singleton") @@ -46,6 +51,9 @@ public class DatatablesApiResource { private final ReadWriteNonCoreDataService readWriteNonCoreDataService; private final ToApiJsonSerializer toApiJsonSerializer; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final static org.slf4j.Logger logger = LoggerFactory.getLogger(DatatablesApiResource.class); + + @Autowired public DatatablesApiResource(final PlatformSecurityContext context, final GenericDataService genericDataService, @@ -109,11 +117,12 @@ public class DatatablesApiResource { @Path("register/{datatable}/{apptable}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String registerDatatable(@PathParam("datatable") final String datatable, @PathParam("apptable") final String apptable) { + public String registerDatatable(@PathParam("datatable") final String datatable, @PathParam("apptable") final String apptable,final String apiRequestBodyAsJson) { - this.readWriteNonCoreDataService.registerDatatable(datatable, apptable); + final CommandWrapper commandRequest = new CommandWrapperBuilder().registerDBDatatable(datatable,apptable).withJson(apiRequestBodyAsJson).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - final CommandProcessingResult result = new CommandProcessingResultBuilder().withResourceIdAsString(datatable).build(); return this.toApiJsonSerializer.serialize(result); } @@ -173,6 +182,8 @@ public class DatatablesApiResource { public String getDatatableManyEntry(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId, @PathParam("datatableId") final Long datatableId, @QueryParam("order") final String order, @Context final UriInfo uriInfo) { + logger.debug("::1 we came in the getDatatbleManyEntry apiRessource method"); + this.context.authenticatedUser().validateHasDatatableReadPermission(datatable); final GenericResultsetData results = this.readWriteNonCoreDataService.retrieveDataTableGenericResultSet(datatable, apptableId, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DataTableValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DataTableValidator.java new file mode 100644 index 000000000..1096d1bbb --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DataTableValidator.java @@ -0,0 +1,51 @@ +package org.mifosplatform.infrastructure.dataqueries.data; + +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang.StringUtils; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.ApiParameterError; +import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; +import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; +import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.mifosplatform.infrastructure.dataqueries.api.DataTableApiConstant.*; + +@Component +public class DataTableValidator { + + private final FromJsonHelper fromApiJsonHelper; + + @Autowired + public DataTableValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } + + public void validateDataTableRegistration(final String json) { + + + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, REGISTER_PARAMS); + + final List dataValidationErrors = new ArrayList(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(DATATABLE_RESOURCE_NAME); + final JsonElement element = this.fromApiJsonHelper.parse(json); + + if (this.fromApiJsonHelper.parameterExists(categoryParamName, element)) { + + final Integer category = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(categoryParamName,element); + baseDataValidator.reset().parameter(categoryParamName).value(category).isOneOfTheseValues(new Integer[]{CATEGORY_PPI,CATEGORY_DEFAULT}); + } + + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } + + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java index fd111b1dc..13dad9921 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java @@ -19,6 +19,7 @@ public class DatatableData { @SuppressWarnings("unused") private final List columnHeaderData; + public static DatatableData create(final String applicationTableName, final String registeredTableName, final List columnHeaderData) { return new DatatableData(applicationTableName, registeredTableName, columnHeaderData); @@ -29,5 +30,6 @@ public class DatatableData { this.applicationTableName = applicationTableName; this.registeredTableName = registeredTableName; this.columnHeaderData = columnHeaderData; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnValueData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnValueData.java index bdb4d7866..e5b65766e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnValueData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnValueData.java @@ -13,10 +13,17 @@ public class ResultsetColumnValueData { private final int id; private final String value; + private final Integer score; public ResultsetColumnValueData(final int id, final String value) { this.id = id; this.value = value; + this.score = null; + } + public ResultsetColumnValueData(final int id, final String value, final int score) { + this.id = id; + this.value = value; + this.score = score; } public boolean matches(final String match) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java new file mode 100644 index 000000000..0771775de --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java @@ -0,0 +1,35 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.infrastructure.dataqueries.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; +import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class RegisterDatatableCommandHandler implements NewCommandSourceHandler { + + private final ReadWriteNonCoreDataService writePlatformService; + + @Autowired + public RegisterDatatableCommandHandler(final ReadWriteNonCoreDataService writePlatformService) { + this.writePlatformService = writePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + + this.writePlatformService.registerDatatable(command); + + return new CommandProcessingResultBuilder().withResourceIdAsString(this.writePlatformService.getDataTableName(command.getUrl())).build(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java index df7fc1b8b..6a9926fc4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java @@ -17,6 +17,8 @@ import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnHeaderDa import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnValueData; import org.mifosplatform.infrastructure.dataqueries.data.ResultsetRowData; import org.mifosplatform.infrastructure.dataqueries.exception.DatatableNotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; @@ -28,11 +30,13 @@ public class GenericDataServiceImpl implements GenericDataService { private final JdbcTemplate jdbcTemplate; private final DataSource dataSource; + private final static Logger logger = LoggerFactory.getLogger(GenericDataServiceImpl.class); @Autowired public GenericDataServiceImpl(final RoutingDataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(this.dataSource); + } @Override @@ -40,6 +44,7 @@ public class GenericDataServiceImpl implements GenericDataService { final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); + final List columnHeaders = new ArrayList(); final List resultsetDataRows = new ArrayList(); @@ -171,6 +176,8 @@ public class GenericDataServiceImpl implements GenericDataService { @Override public List fillResultsetColumnHeaders(final String datatable) { + logger.debug("::3 Was inside the fill ResultSetColumnHeader"); + final SqlRowSet columnDefinitions = getDatatableMetaData(datatable); final List columnHeaders = new ArrayList(); @@ -189,13 +196,16 @@ public class GenericDataServiceImpl implements GenericDataService { List columnValues = new ArrayList(); String codeName = null; if ("varchar".equalsIgnoreCase(columnType)) { + final int codePosition = columnName.indexOf("_cv"); if (codePosition > 0) { codeName = columnName.substring(0, codePosition); + columnValues = retreiveColumnValues(codeName); } } else if ("int".equalsIgnoreCase(columnType)) { + final int codePosition = columnName.indexOf("_cd"); if (codePosition > 0) { codeName = columnName.substring(0, codePosition); @@ -228,9 +238,10 @@ public class GenericDataServiceImpl implements GenericDataService { */ private List retreiveColumnValues(final String codeName) { + final List columnValues = new ArrayList(); - final String sql = "select v.id, v.code_value from m_code m " + " join m_code_value v on v.code_id = m.id " + final String sql = "select v.id, v.code_score, v.code_value from m_code m " + " join m_code_value v on v.code_id = m.id " + " where m.code_name = '" + codeName + "' order by v.order_position, v.id"; final SqlRowSet rsValues = this.jdbcTemplate.queryForRowSet(sql); @@ -239,8 +250,9 @@ public class GenericDataServiceImpl implements GenericDataService { while (rsValues.next()) { final Integer id = rsValues.getInt("id"); final String codeValue = rsValues.getString("code_value"); + final Integer score = rsValues.getInt("code_score"); - columnValues.add(new ResultsetColumnValueData(id, codeValue)); + columnValues.add(new ResultsetColumnValueData(id, codeValue, score)); } return columnValues; @@ -248,6 +260,7 @@ public class GenericDataServiceImpl implements GenericDataService { private List retreiveColumnValues(final Integer codeId) { + final List columnValues = new ArrayList(); if (codeId != null) { final String sql = "select v.id, v.code_value from m_code_value v where v.code_id =" + codeId diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java index e50a41cb1..d35ba2f82 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java @@ -6,11 +6,13 @@ package org.mifosplatform.infrastructure.dataqueries.service; import java.util.List; +import java.util.Map; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; +import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnHeaderData; import org.springframework.security.access.prepost.PreAuthorize; public interface ReadWriteNonCoreDataService { @@ -20,7 +22,13 @@ public interface ReadWriteNonCoreDataService { DatatableData retrieveDatatable(String datatable); @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") - void registerDatatable(String datatable, String appTable); + void registerDatatable(JsonCommand command); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") + void registerDatatable(String dataTableName,String applicationTableName); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") + void registerDatatable(JsonCommand command,String permissionTable); @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'DEREGISTER_DATATABLE')") void deregisterDatatable(String datatable); @@ -34,6 +42,7 @@ public interface ReadWriteNonCoreDataService { void deleteDatatable(String datatableName); CommandProcessingResult createNewDatatableEntry(String datatable, Long appTableId, JsonCommand command); + CommandProcessingResult createPPIEntry(String datatable, Long appTableId, JsonCommand command); CommandProcessingResult updateDatatableEntryOneToOne(String datatable, Long appTableId, JsonCommand command); @@ -43,4 +52,9 @@ public interface ReadWriteNonCoreDataService { CommandProcessingResult deleteDatatableEntry(String datatable, Long appTableId, Long datatableId); + String getTableName(String Url); + String getDataTableName(String Url); + + + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java index e09f2d44a..59d389c15 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java @@ -20,9 +20,11 @@ import org.apache.commons.lang.StringUtils; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.GenericJDBCException; import org.hibernate.exception.SQLGrammarException; +import org.hibernate.service.config.internal.ConfigurationServiceImpl; import org.joda.time.LocalDate; import org.mifosplatform.infrastructure.codes.service.CodeReadPlatformService; import org.mifosplatform.infrastructure.configuration.domain.ConfigurationDomainService; + import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.ApiParameterError; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; @@ -35,10 +37,8 @@ import org.mifosplatform.infrastructure.core.serialization.DatatableCommandFromA import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; import org.mifosplatform.infrastructure.core.serialization.JsonParserHelper; import org.mifosplatform.infrastructure.core.service.RoutingDataSource; -import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; -import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; -import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnHeaderData; -import org.mifosplatform.infrastructure.dataqueries.data.ResultsetRowData; +import org.mifosplatform.infrastructure.dataqueries.api.DataTableApiConstant; +import org.mifosplatform.infrastructure.dataqueries.data.*; import org.mifosplatform.infrastructure.dataqueries.exception.DatatableNotFoundException; import org.mifosplatform.infrastructure.dataqueries.exception.DatatableSystemErrorException; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; @@ -46,6 +46,7 @@ import org.mifosplatform.useradministration.domain.AppUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.mifosplatform.infrastructure.configuration.service.GlobalConfigurationWritePlatformServiceJpaRepositoryImpl; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.EmptyResultDataAccessException; @@ -89,12 +90,15 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private final DatatableCommandFromApiJsonDeserializer fromApiJsonDeserializer; private final ConfigurationDomainService configurationDomainService; private final CodeReadPlatformService codeReadPlatformService; + private final DataTableValidator dataTableValidator; - @Autowired + //private final GlobalConfigurationWritePlatformServiceJpaRepositoryImpl configurationWriteService; + + @Autowired(required = true) public ReadWriteNonCoreDataServiceImpl(final RoutingDataSource dataSource, final PlatformSecurityContext context, final FromJsonHelper fromJsonHelper, final GenericDataService genericDataService, final DatatableCommandFromApiJsonDeserializer fromApiJsonDeserializer, final CodeReadPlatformService codeReadPlatformService, - final ConfigurationDomainService configurationDomainService) { + final ConfigurationDomainService configurationDomainService, final DataTableValidator dataTableValidator) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(this.dataSource); this.context = context; @@ -104,6 +108,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.codeReadPlatformService = codeReadPlatformService; this.configurationDomainService = configurationDomainService; + this.dataTableValidator = dataTableValidator; + //this.configurationWriteService = configurationWriteService; } @Override @@ -171,14 +177,100 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ @Transactional @Override - public void registerDatatable(final String dataTableName, final String applicationTableName) { + public void registerDatatable(final String dataTableName, final String applicationTableName) + { + + Integer category = DataTableApiConstant.CATEGORY_DEFAULT; + + final String permissionSql = this._getPermissionSql(dataTableName); + this._registerDataTable(applicationTableName, dataTableName, category, permissionSql); + + } + + @Transactional + @Override + public void registerDatatable(final JsonCommand command) { + + final String applicationTableName = this.getTableName(command.getUrl()); + final String dataTableName = this.getDataTableName(command.getUrl()); + + Integer category = this.getCategory(command); + + this.dataTableValidator.validateDataTableRegistration(command.json()); + final String permissionSql = this._getPermissionSql(dataTableName); + this._registerDataTable(applicationTableName, dataTableName, category, permissionSql); + + } + + @Transactional + @Override + public void registerDatatable(final JsonCommand command,final String permissionSql) + { + final String applicationTableName = this.getTableName(command.getUrl()); + final String dataTableName = this.getDataTableName(command.getUrl()); + + Integer category = this.getCategory(command); + + this.dataTableValidator.validateDataTableRegistration(command.json()); + + this._registerDataTable(applicationTableName,dataTableName,category,permissionSql); + + } + + @Transactional + private void _registerDataTable(final String applicationTableName, + final String dataTableName, + final Integer category, + final String permissionsSql) + { validateAppTable(applicationTableName); assertDataTableExists(dataTableName); - final String registerDatatableSql = "insert into x_registered_table (registered_table_name, application_table_name) values ('" - + dataTableName + "', '" + applicationTableName + "')"; + final String registerDatatableSql = "insert into x_registered_table (registered_table_name, application_table_name,category) values ('" + + dataTableName + "', '" + applicationTableName + "', '" + category + "')"; + + try { + + + final String[] sqlArray = { registerDatatableSql, permissionsSql }; + this.jdbcTemplate.batchUpdate(sqlArray); + + // add the registered table to the config if it is a ppi + if(this.isSurveyCategory(category)) + { + this.jdbcTemplate.execute("insert into c_configuration (name, value, enabled ) values('"+dataTableName+"', '0','0')"); + } + + } + /*** + * Strangely, a Hibernate contraint violation exception is thrown + ****/ + catch (final ConstraintViolationException cve) { + final Throwable realCause = cve.getCause(); + // even if duplicate is only due to permission duplicate, okay to + // show duplicate datatable error msg + if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( + "error.msg.datatable.registered", "Datatable `" + dataTableName + + "` is already registered against an application table.", "dataTableName", dataTableName); } + } catch (final DataIntegrityViolationException dve) { + final Throwable realCause = dve.getMostSpecificCause(); + // even if duplicate is only due to permission duplicate, okay to + // show duplicate datatable error msg + if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( + "error.msg.datatable.registered", "Datatable `" + dataTableName + + "` is already registered against an application table.", "dataTableName", dataTableName); } + logAsErrorUnexpectedDataIntegrityException(dve); + throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } + + + } + + private String _getPermissionSql(final String dataTableName) + { final String createPermission = "'CREATE_" + dataTableName + "'"; final String createPermissionChecker = "'CREATE_" + dataTableName + "_CHECKER'"; final String readPermission = "'READ_" + dataTableName + "'"; @@ -187,7 +279,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final String deletePermission = "'DELETE_" + dataTableName + "'"; final String deletePermissionChecker = "'DELETE_" + dataTableName + "_CHECKER'"; - final String permissionsSql = "insert into m_permission (grouping, code, action_name, entity_name, can_maker_checker) values " + return "insert into m_permission (grouping, code, action_name, entity_name, can_maker_checker) values " + "('datatable', " + createPermission + ", 'CREATE', '" @@ -223,33 +315,32 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ + ", 'DELETE', '" + dataTableName + "', false)"; - try { - final String[] sqlArray = { registerDatatableSql, permissionsSql }; - this.jdbcTemplate.batchUpdate(sqlArray); + } - } - /*** - * Strangely, a Hibernate contraint violation exception is thrown - ****/ - catch (final ConstraintViolationException cve) { - final Throwable realCause = cve.getCause(); - // even if duplicate is only due to permission duplicate, okay to - // show duplicate datatable error msg - if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( - "error.msg.datatable.registered", "Datatable `" + dataTableName - + "` is already registered against an application table.", "dataTableName", dataTableName); } - } catch (final DataIntegrityViolationException dve) { - final Throwable realCause = dve.getMostSpecificCause(); - // even if duplicate is only due to permission duplicate, okay to - // show duplicate datatable error msg - if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( - "error.msg.datatable.registered", "Datatable `" + dataTableName - + "` is already registered against an application table.", "dataTableName", dataTableName); } - logAsErrorUnexpectedDataIntegrityException(dve); - throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } + private Integer getCategory(final JsonCommand command) + { + Integer category = command.integerValueOfParameterNamedDefaultToNullIfZero(DataTableApiConstant.categoryParamName); + if(category ==null) category = DataTableApiConstant.CATEGORY_DEFAULT; + return category; + } + private boolean isSurveyCategory(final Integer category) + { + return category.equals(DataTableApiConstant.CATEGORY_PPI); + } + + public String getDataTableName(String url){ + + String [] urlParts = url.split("/"); + + return urlParts[3]; + + } + + public String getTableName(String url) + { + String [] urlParts = url.split("/"); + return urlParts[4]; } @Transactional @@ -265,10 +356,13 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final String deleteRegisteredDatatableSql = "delete from x_registered_table where registered_table_name = '" + datatable + "'"; - String[] sqlArray = new String[3]; + final String deleteFromConfigurationSql = "delete from c_configuration where name ='"+datatable+"'"; + + String[] sqlArray = new String[4]; sqlArray[0] = deleteRolePermissionsSql; sqlArray[1] = deletePermissionsSql; sqlArray[2] = deleteRegisteredDatatableSql; + sqlArray[3] = deleteFromConfigurationSql ; this.jdbcTemplate.batchUpdate(sqlArray); } @@ -316,6 +410,47 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } + public CommandProcessingResult createPPIEntry(final String dataTableName, final Long appTableId, final JsonCommand command) { + + try { + final String appTable = queryForApplicationTableName(dataTableName); + final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); + + final List columnHeaders = this.genericDataService.fillResultsetColumnHeaders(dataTableName); + + final Type typeOfMap = new TypeToken>() {}.getType(); + final Map dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json()); + + final String sql = getAddSqlWithScore(columnHeaders, dataTableName, getFKField(appTable), appTableId, dataParams); + + this.jdbcTemplate.update(sql); + + return commandProcessingResult; // + + } catch (final ConstraintViolationException dve) { + // NOTE: jdbctemplate throws a + // org.hibernate.exception.ConstraintViolationException even though + // it should be a DataAccessException? + final Throwable realCause = dve.getCause(); + if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( + "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, appTableId); } + + logAsErrorUnexpectedDataIntegrityException(dve); + throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } catch (final DataAccessException dve) { + final Throwable realCause = dve.getMostSpecificCause(); + if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( + "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, appTableId); } + + logAsErrorUnexpectedDataIntegrityException(dve); + throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } + } + private boolean isRegisteredDataTable(final String name) { // PERMITTED datatables final String sql = "select if((exists (select 1 from x_registered_table where registered_table_name = ?)) = 1, 'true', 'false')"; @@ -940,6 +1075,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public GenericResultsetData retrieveDataTableGenericResultSet(final String dataTableName, final Long appTableId, final String order, final Long id) { + final String appTable = queryForApplicationTableName(dataTableName); checkMainResourceExistsWithinScope(appTable, appTableId); @@ -1178,6 +1314,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ pValueWrite = "null"; } else { pValueWrite = singleQuote + this.genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote; + + } columnName = "`" + key + "`"; insertColumns += ", " + columnName; @@ -1187,9 +1325,68 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ addSql = "insert into `" + datatable + "` (`" + fkName + "` " + insertColumns + ")" + " select " + appTableId + " as id" + selectColumns; + logger.info(addSql); + return addSql; } + /** + * This method is used special for ppi cases + * Where the score need to be computed + * @param columnHeaders + * @param datatable + * @param fkName + * @param appTableId + * @param queryParams + * @return + */ + public String getAddSqlWithScore(final List columnHeaders, final String datatable, final String fkName, + final Long appTableId, final Map queryParams) { + + final Map affectedColumns = getAffectedColumns(columnHeaders, queryParams, fkName); + + String pValueWrite = ""; + String addSql = ""; + String scoresId = " "; + final String singleQuote = "'"; + + String insertColumns = ""; + String selectColumns = ""; + String columnName = ""; + String pValue = null; + for (final String key : affectedColumns.keySet()) { + pValue = affectedColumns.get(key); + + if (StringUtils.isEmpty(pValue)) { + pValueWrite = "null"; + } else { + pValueWrite = singleQuote + this.genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote; + + scoresId +=pValueWrite +" ,"; + + + } + columnName = "`" + key + "`"; + insertColumns += ", " + columnName; + selectColumns += "," + pValueWrite + " as " + columnName; + } + + + scoresId = scoresId.replaceAll(" ,$", ""); + + addSql = "insert into `" + datatable + "` (`" + fkName + "` " + insertColumns + ")" + " select " + appTableId + " as id" + + selectColumns; + + String vaddSql = "insert into `" + datatable + "` (`" + fkName + "` " + insertColumns + ", `score` )" + " select " + appTableId + " as id" + + selectColumns + " , ( SELECT SUM( code_score ) FROM m_code_value WHERE m_code_value.id IN (" + scoresId + " ) ) as score"; + + + + logger.info(vaddSql); + + return vaddSql; + } + private String getUpdateSql(final String datatable, final String keyFieldName, final Long keyFieldValue, final Map changedColumns) { @@ -1265,7 +1462,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ throw new PlatformDataIntegrityException("error.msg.invalid.columnName", "Parameter Column Name: " + key + " not found"); } - private Map getAffectedColumns(final List columnHeaders, + public Map getAffectedColumns(final List columnHeaders, final Map queryParams, final String keyFieldName) { final String dateFormat = queryParams.get("dateFormat"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiConstants.java new file mode 100644 index 000000000..06fc754c4 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiConstants.java @@ -0,0 +1,25 @@ +package org.mifosplatform.infrastructure.survey.api; + +import org.mifosplatform.infrastructure.survey.data.LikelihoodStatus; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by Cieyou on 3/12/14. + */ +public class LikelihoodApiConstants { + + public static final String ACTIVE = "active"; + + public static final String LIKELIHOOD_RESOURCE_NAME = "likelihood"; + + public static final Set UPDATE_LIKELIHOOD_DATA_PARAMETERS = new HashSet(Arrays.asList(ACTIVE)); + + public static final Set VALID_LIKELIHOOD_ENABLED_VALUES = new HashSet( + Arrays.asList( + LikelihoodStatus.DISABLED, + LikelihoodStatus.ENABLED + )); +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java new file mode 100644 index 000000000..00ebd9f2f --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java @@ -0,0 +1,95 @@ +package org.mifosplatform.infrastructure.survey.api; + +import org.mifosplatform.commands.domain.CommandWrapper; +import org.mifosplatform.commands.service.CommandWrapperBuilder; +import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.infrastructure.survey.data.LikelihoodData; +import org.mifosplatform.infrastructure.survey.service.ReadLikelihoodService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +/** + * Created by Cieyou on 3/12/14. + */ +@Path("/likelihood") +@Component +@Scope("singleton") +public class LikelihoodApiResource { + + + private final static Logger logger = LoggerFactory.getLogger(PovertyLineApiResource.class); + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final PlatformSecurityContext context; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final ReadLikelihoodService readService; + + + @Autowired + LikelihoodApiResource(final PlatformSecurityContext context, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final ReadLikelihoodService readService) { + + this.context = context; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.readService = readService; + + + } + + @GET + @Path("{ppiName}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveAll(@PathParam("ppiName") final String ppiName){ + + this.context.authenticatedUser().validateHasReadPermission(PovertyLineApiConstants.POVERTY_LINE_RESOURCE_NAME); + + List likelihoodData = this.readService.retrieveAll(ppiName); + return this.toApiJsonSerializer.serialize(likelihoodData); + + } + + @GET + @Path("{ppiName}/{likelihoodId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieve(@PathParam("likelihoodId") final Long likelihoodId){ + + this.context.authenticatedUser().validateHasReadPermission(PovertyLineApiConstants.POVERTY_LINE_RESOURCE_NAME); + + LikelihoodData likelihoodData = this.readService.retrieve(likelihoodId); + return this.toApiJsonSerializer.serialize(likelihoodData); + + } + + @PUT + @Path("{likelihoodId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String update(@PathParam("likelihoodId") final Long likelihoodId, final String apiRequestBodyAsJson){ + + this.context.authenticatedUser().validateHasReadPermission(PovertyLineApiConstants.POVERTY_LINE_RESOURCE_NAME); + + final CommandWrapper commandRequest = new CommandWrapperBuilder() // + .updateLikelihood(likelihoodId) // + .withJson(apiRequestBodyAsJson) // + .build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiConstants.java new file mode 100644 index 000000000..a8c4ed270 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiConstants.java @@ -0,0 +1,12 @@ +package org.mifosplatform.infrastructure.survey.api; + +import org.springframework.stereotype.Service; + +/** + * Created by Cieyou on 3/11/14. + */ + +public class PovertyLineApiConstants { + + final static String POVERTY_LINE_RESOURCE_NAME = "PovertyLine"; +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiResource.java new file mode 100644 index 000000000..b4c522d42 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/PovertyLineApiResource.java @@ -0,0 +1,82 @@ +package org.mifosplatform.infrastructure.survey.api; + +import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; +import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.infrastructure.survey.data.LikeliHoodPovertyLineData; +import org.mifosplatform.infrastructure.survey.data.PovertyLineData; +import org.mifosplatform.infrastructure.survey.data.PpiPovertyLineData; +import org.mifosplatform.infrastructure.survey.service.PovertyLineService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * Created by Cieyou on 3/11/14. + */ +@Path("/povertyLine") +@Component +@Scope("singleton") +public class PovertyLineApiResource { + + private final static Logger logger = LoggerFactory.getLogger(PovertyLineApiResource.class); + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final DefaultToApiJsonSerializer likelihoodToApiJsonSerializer; + // private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final PlatformSecurityContext context; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final PovertyLineService readService; + + + @Autowired + PovertyLineApiResource(final PlatformSecurityContext context, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final PovertyLineService readService, + final DefaultToApiJsonSerializer likelihoodToApiJsonSerializer) { + + this.context = context; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.readService = readService; + this.likelihoodToApiJsonSerializer = likelihoodToApiJsonSerializer; + + } + + @GET + @Path("{ppiName}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveAll(@PathParam("ppiName") final String ppiName){ + + this.context.authenticatedUser().validateHasReadPermission(PovertyLineApiConstants.POVERTY_LINE_RESOURCE_NAME); + + PpiPovertyLineData povertyLine = this.readService.retrieveAll(ppiName); + return this.toApiJsonSerializer.serialize(povertyLine); + + } + @GET + @Path("{ppiName}/{likelihoodId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveAll(@PathParam("ppiName") final String ppiName,@PathParam("likelihoodId") final Long likelihoodId){ + + this.context.authenticatedUser().validateHasReadPermission(PovertyLineApiConstants.POVERTY_LINE_RESOURCE_NAME); + + LikeliHoodPovertyLineData likeliHoodPovertyLineData = this.readService.retrieveForLikelihood(ppiName, likelihoodId); + + return this.likelihoodToApiJsonSerializer.serialize(likeliHoodPovertyLineData); + + } + + + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiConstants.java new file mode 100644 index 000000000..7a0ca862c --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiConstants.java @@ -0,0 +1,10 @@ +package org.mifosplatform.infrastructure.survey.api; + +/** + * Created by Cieyou on 2/27/14. + */ +public class SurveyApiConstants { + + + final static String SURVEY_RESOURCE_NAME ="Survey"; +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java new file mode 100644 index 000000000..f20b4d1e7 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java @@ -0,0 +1,179 @@ +package org.mifosplatform.infrastructure.survey.api; + +import com.google.gson.JsonElement; +import org.apache.commons.lang.StringUtils; +import org.mifosplatform.commands.domain.CommandWrapper; +import org.mifosplatform.commands.service.CommandWrapperBuilder; +import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; +import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; +import org.mifosplatform.infrastructure.core.api.JsonQuery; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; +import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; +import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; +import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; +import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; +import org.mifosplatform.infrastructure.dataqueries.service.GenericDataService; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.infrastructure.survey.data.ClientScoresOverview; +import org.mifosplatform.infrastructure.survey.data.SurveyData; +import org.mifosplatform.infrastructure.survey.data.SurveyDataTableData; +import org.mifosplatform.infrastructure.survey.service.ReadSurveyService; +import org.mifosplatform.infrastructure.survey.service.ReadSurveyServiceImpl; +import org.mifosplatform.portfolio.client.domain.Client; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.lang.reflect.Array; +import java.util.Collection; +import java.util.List; + +/** + * Created by Cieyou on 2/27/14. + */ +@Path("/survey") +@Component +@Scope("singleton") +public class SurveyApiResource { + + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final DefaultToApiJsonSerializer toApiJsonClientScoreOverviewSerializer; + private final PlatformSecurityContext context; + private final ReadSurveyService readSurveyService; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final GenericDataService genericDataService; + + private final static Logger logger = LoggerFactory.getLogger(SurveyApiResource.class); + + @Autowired + public SurveyApiResource(final DefaultToApiJsonSerializer toApiJsonSerializer, + final PlatformSecurityContext context, + final ReadSurveyService readSurveyService, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonClientScoreOverviewSerializer, + final GenericDataService genericDataService){ + + this.toApiJsonSerializer = toApiJsonSerializer; + this.context = context; + this.readSurveyService = readSurveyService; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonClientScoreOverviewSerializer = toApiJsonClientScoreOverviewSerializer; + this.genericDataService = genericDataService; + } + + + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveSurveys(@Context final UriInfo uriInfo) { + + this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); + + List surveys = this.readSurveyService.retrieveAllSurveys(); + return this.toApiJsonSerializer.serialize(surveys); + } + + + @GET + @Path("{surveyName}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveSurvey(@PathParam("surveyName") final String surveyName) { + + this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); + + SurveyDataTableData surveys = this.readSurveyService.retrieveSurvey(surveyName); + + return this.toApiJsonSerializer.serialize(surveys); + + } + + @POST + @Path("{surveyName}/{apptableId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String createDatatableEntry(@PathParam("surveyName") final String datatable, @PathParam("apptableId") final Long apptableId, + final String apiRequestBodyAsJson) { + + final CommandWrapper commandRequest = new CommandWrapperBuilder() // + .fullFilSurvey(datatable, apptableId) // + .withJson(apiRequestBodyAsJson) // + .build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + } + + @GET + @Path("{surveyName}/{clientId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getClientSurveyOverview(@PathParam("surveyName") final String surveyName, @PathParam("clientId") final Long clientId) { + + + this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); + + List scores = this.readSurveyService.retrieveClientSurveyScoreOverview(surveyName, clientId); + + return this.toApiJsonClientScoreOverviewSerializer.serialize(scores); + } + + @GET + @Path("{surveyName}/{clientId}/{entryId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getSurveyEntry(@PathParam("surveyName") final String surveyName, @PathParam("clientId") final Long clientId, @PathParam("entryId") final Long entryId) { + + + this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); + + final GenericResultsetData results = this.readSurveyService.retrieveSurveyEntry(surveyName, clientId,entryId); + + return this.genericDataService.generateJsonFromGenericResultsetData(results); + + } + + + @PUT + @Path("register/{surveyName}/{apptable}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String register(@PathParam("surveyName") final String datatable, @PathParam("apptable") final String apptable, + final String apiRequestBodyAsJson) { + + + final CommandWrapper commandRequest = new CommandWrapperBuilder().registerSurvey( datatable,apptable).withJson(apiRequestBodyAsJson).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + + } + + private boolean is(final String commandParam, final String commandValue) { + return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); + } + + @DELETE + @Path("{surveyName}/{clientId}/{fulfilledId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String deleteDatatableEntries(@PathParam("surveyName") final String surveyName,@PathParam("clientId") final Long clientId, @PathParam("fulfilledId") final Long fulfilledId) { + + final CommandWrapper commandRequest = new CommandWrapperBuilder() // + .deleteDatatable(surveyName,clientId, fulfilledId) // + .build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java new file mode 100644 index 000000000..43a1a5138 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java @@ -0,0 +1,32 @@ +package org.mifosplatform.infrastructure.survey.data; + +import org.joda.time.LocalDate; + +/** + * Created by Cieyou on 3/18/14. + */ +public class ClientScoresOverview { + + final private long id ; + final private String likelihoodCode ; + final private String likelihoodName; + final private long score; + final private Double povertyLine; + final private LocalDate date; + + public ClientScoresOverview(final String likelihoodCode, + final String likelihoodName, + final long score, + final Double povertyLine, + final LocalDate date, + final long resourceId) { + + this.likelihoodCode = likelihoodCode; + this.likelihoodName = likelihoodName; + this.score = score; + this.povertyLine = povertyLine; + this.date = date; + this.id = resourceId; + + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikeliHoodPovertyLineData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikeliHoodPovertyLineData.java new file mode 100644 index 000000000..e802ac3d7 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikeliHoodPovertyLineData.java @@ -0,0 +1,38 @@ +package org.mifosplatform.infrastructure.survey.data; + +import java.util.List; + +/** + * Created by Cieyou on 3/11/14. + */ +public class LikeliHoodPovertyLineData { + + final long resourceId; + final String likeliHoodName; + final String likeliHoodCode; + final long enabled; + List povertyLineData; + + public LikeliHoodPovertyLineData(final long resourceId, final List povertyLineData, + final String likeliHoodName, + final String likeliHoodCode, + final long enabled){ + this.resourceId = resourceId; + this.povertyLineData = povertyLineData; + this.likeliHoodName = likeliHoodName; + this.likeliHoodCode = likeliHoodCode; + this.enabled = enabled; + + } + + + public void addPovertyLine(PovertyLineData povertyLineData) + { + this.povertyLineData.add(povertyLineData); + } + + public void setEnabled(final Long enabled) + { + // this.enabled = enabled; + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodData.java new file mode 100644 index 000000000..843db080d --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodData.java @@ -0,0 +1,27 @@ +package org.mifosplatform.infrastructure.survey.data; + +import java.util.List; + +/** + * Created by Cieyou on 3/12/14. + */ +public class LikelihoodData { + + final long resourceId; + final String likeliHoodName; + final String likeliHoodCode; + final long enabled; + + + public LikelihoodData(final long resourceId, + final String likeliHoodName, + final String likeliHoodCode, + final long enabled){ + this.resourceId = resourceId; + this.likeliHoodName = likeliHoodName; + this.likeliHoodCode = likeliHoodCode; + this.enabled = enabled; + + } + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodDataValidator.java new file mode 100644 index 000000000..8ac384f44 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodDataValidator.java @@ -0,0 +1,55 @@ +package org.mifosplatform.infrastructure.survey.data; + +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang.StringUtils; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.ApiParameterError; +import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; +import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; +import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.mifosplatform.infrastructure.survey.api.LikelihoodApiConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Created by Cieyou on 3/12/14. + */ + +@Component +public class LikelihoodDataValidator { + + private final FromJsonHelper fromApiJsonHelper; + + @Autowired + public LikelihoodDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } + + public void validateForUpdate(final JsonCommand command) { + final String json = command.json(); + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, LikelihoodApiConstants.UPDATE_LIKELIHOOD_DATA_PARAMETERS); + + final List dataValidationErrors = new ArrayList(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(LikelihoodApiConstants.LIKELIHOOD_RESOURCE_NAME); + final JsonElement element = this.fromApiJsonHelper.parse(json); + + if (this.fromApiJsonHelper.parameterExists(LikelihoodApiConstants.ACTIVE, element)) { + final boolean enabledBool = this.fromApiJsonHelper.extractBooleanNamed(LikelihoodApiConstants.ACTIVE, element); + + baseDataValidator.reset().parameter(LikelihoodApiConstants.ACTIVE).value(enabledBool).validateForBooleanValue(); + } + + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } + + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodStatus.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodStatus.java new file mode 100644 index 000000000..5fe4d2f81 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/LikelihoodStatus.java @@ -0,0 +1,10 @@ +package org.mifosplatform.infrastructure.survey.data; + +/** + * Created by Cieyou on 3/12/14. + */ +public class LikelihoodStatus { + + public final static long ENABLED = 200; + public final static long DISABLED =100; +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PovertyLineData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PovertyLineData.java new file mode 100644 index 000000000..22960f51f --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PovertyLineData.java @@ -0,0 +1,23 @@ +package org.mifosplatform.infrastructure.survey.data; + +/** + * Created by Cieyou on 3/11/14. + */ +public class PovertyLineData { + + final Long resourceId; + final Long scoreFrom; + final Long scoreTo; + final Double povertyLine; + + public PovertyLineData(final Long resourceId, + final Long scoreFrom, + final Long scoreTo, + final Double povertyLine){ + + this.resourceId = resourceId; + this.scoreTo = scoreTo; + this.scoreFrom = scoreFrom; + this.povertyLine = povertyLine; + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PpiPovertyLineData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PpiPovertyLineData.java new file mode 100644 index 000000000..e6236d2c1 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/PpiPovertyLineData.java @@ -0,0 +1,23 @@ +package org.mifosplatform.infrastructure.survey.data; + +import java.util.List; + +/** + * Created by Cieyou on 3/11/14. + */ +public class PpiPovertyLineData { + + final String ppi; + final List likeliHoodPovertyLineData; + + + public PpiPovertyLineData(final List likeliHoodPovertyLineData, + final String ppi){ + + this.likeliHoodPovertyLineData = likeliHoodPovertyLineData; + this.ppi = ppi; + + } + + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyData.java new file mode 100644 index 000000000..04bd57b3c --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyData.java @@ -0,0 +1,7 @@ +package org.mifosplatform.infrastructure.survey.data; + +/** + * Created by Cieyou on 2/27/14. + */ +public class SurveyData { +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyDataTableData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyDataTableData.java new file mode 100644 index 000000000..197b026ec --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/SurveyDataTableData.java @@ -0,0 +1,30 @@ +package org.mifosplatform.infrastructure.survey.data; + +import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; +import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnHeaderData; + +import java.util.List; + +/** + * Created by Cieyou on 2/27/14. + */ +public class SurveyDataTableData { + + @SuppressWarnings("unused") + private final DatatableData datatableData; + + @SuppressWarnings("unused") + private final boolean enabled ; + + + + public static SurveyDataTableData create(final DatatableData datatableData, final boolean enabled) { + + return new SurveyDataTableData(datatableData, enabled); + } + + private SurveyDataTableData(final DatatableData datatableData, final boolean enabled) { + this.datatableData = datatableData; + this.enabled = enabled; + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java new file mode 100644 index 000000000..0eeb646ce --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java @@ -0,0 +1,68 @@ +package org.mifosplatform.infrastructure.survey.domain; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.survey.api.LikelihoodApiConstants; +import org.mifosplatform.infrastructure.survey.data.LikelihoodStatus; +import org.springframework.data.jpa.domain.AbstractPersistable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Created by Cieyou on 3/12/14. + */ +@Entity +@Table(name="ppi_likelihoods_ppi") +public final class Likelihood extends AbstractPersistable { + + @Column(name = "ppi_name", nullable = false) + private String ppiName; + + @Column(name = "likelihood_id", nullable = false) + private Long likelihoodId; + + @Column(name = "enabled", nullable = false) + private Long enabled; + + public Map update(final JsonCommand command) + { + final Map actualChanges = new LinkedHashMap(7); + + final boolean enabled = command.booleanPrimitiveValueOfParameterNamed(LikelihoodApiConstants.ACTIVE); + + Long changeToValue = null; + + if(enabled){ + changeToValue = LikelihoodStatus.ENABLED; + }else{ + changeToValue = LikelihoodStatus.DISABLED; + } + + + if(!changeToValue.equals(this.enabled)) + { + actualChanges.put(LikelihoodApiConstants.ACTIVE,enabled); + this.enabled = changeToValue; + } + + return actualChanges; + } + + public boolean isActivateCommand(final JsonCommand command) + { + return command.booleanPrimitiveValueOfParameterNamed(LikelihoodApiConstants.ACTIVE); + } + + public String getPpiName() { + return ppiName; + } + + @Override + public Long getId() { + return super.getId(); + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java new file mode 100644 index 000000000..ac0dd02fa --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java @@ -0,0 +1,15 @@ +package org.mifosplatform.infrastructure.survey.domain; + + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +import java.util.List; + +/** + * Created by Cieyou on 3/12/14. + */ +public interface LikelihoodRepository extends JpaRepository, JpaSpecificationExecutor { + + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/FullFilSurveyCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/FullFilSurveyCommandHandler.java new file mode 100644 index 000000000..82a47f75c --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/FullFilSurveyCommandHandler.java @@ -0,0 +1,32 @@ +package org.mifosplatform.infrastructure.survey.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.survey.service.WriteSurveyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Created by Cieyou on 3/12/14. + */ + +@Service +public class FullFilSurveyCommandHandler implements NewCommandSourceHandler { + + + private final WriteSurveyService writePlatformService; + + @Autowired + public FullFilSurveyCommandHandler(final WriteSurveyService writePlatformService) { + this.writePlatformService = writePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + + return this.writePlatformService.fullFillSurvey (command.entityName(),command.entityId(),command); + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/RegisterSurveyCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/RegisterSurveyCommandHandler.java new file mode 100644 index 000000000..e85c5aabc --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/RegisterSurveyCommandHandler.java @@ -0,0 +1,33 @@ +package org.mifosplatform.infrastructure.survey.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.survey.service.WriteLikelihoodService; +import org.mifosplatform.infrastructure.survey.service.WriteSurveyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Created by Cieyou on 3/12/14. + */ + +@Service +public class RegisterSurveyCommandHandler implements NewCommandSourceHandler { + + + private final WriteSurveyService writePlatformService; + + @Autowired + public RegisterSurveyCommandHandler(final WriteSurveyService writePlatformService) { + this.writePlatformService = writePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + + return this.writePlatformService.registerSurvey(command); + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java new file mode 100644 index 000000000..30ad563b8 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java @@ -0,0 +1,32 @@ +package org.mifosplatform.infrastructure.survey.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.survey.service.WriteLikelihoodService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Created by Cieyou on 3/12/14. + */ + +@Service +public class UpdateLikelihoodCommandHandler implements NewCommandSourceHandler { + + + private final WriteLikelihoodService writePlatformService; + + @Autowired + public UpdateLikelihoodCommandHandler(final WriteLikelihoodService writePlatformService) { + this.writePlatformService = writePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + + return this.writePlatformService.update(command.entityId(), command); + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineService.java new file mode 100644 index 000000000..ee39153eb --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineService.java @@ -0,0 +1,19 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.survey.data.LikeliHoodPovertyLineData; +import org.mifosplatform.infrastructure.survey.data.PovertyLineData; +import org.mifosplatform.infrastructure.survey.data.PpiPovertyLineData; + +import java.util.List; + +/** + * Created by Cieyou on 3/11/14. + */ +public interface PovertyLineService { + + PpiPovertyLineData retrieveAll(final String ppiName); + + LikeliHoodPovertyLineData retrieveForLikelihood(final String ppiName,final Long likelihood); + + //PovertyLineData retrieve(); +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineServiceImpl.java new file mode 100644 index 000000000..2aa8bbe28 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/PovertyLineServiceImpl.java @@ -0,0 +1,165 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.core.service.RoutingDataSource; +import org.mifosplatform.infrastructure.survey.data.LikeliHoodPovertyLineData; +import org.mifosplatform.infrastructure.survey.data.PovertyLineData; +import org.mifosplatform.infrastructure.survey.data.PpiPovertyLineData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Cieyou on 3/11/14. + */ +@Service +public class PovertyLineServiceImpl implements PovertyLineService{ + + private final static Logger logger = LoggerFactory.getLogger(PovertyLineService.class); + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + + @Autowired + PovertyLineServiceImpl(final RoutingDataSource dataSource){ + this.dataSource = dataSource; + this.jdbcTemplate = new JdbcTemplate(this.dataSource); + + } + + + @Override + public PpiPovertyLineData retrieveAll(final String ppiName) + { + + final SqlRowSet povertyLines = this._getPovertyLines(ppiName); + + final SqlRowSet likelihoods = this._getLikelihoods(); + + List listOfLikeliHoodPovertyLineData = new ArrayList(); + + while(likelihoods.next()) + { + final String codeName = likelihoods.getString("code"); + + List povertyLineDatas = new ArrayList(); + + // create a new povertyLine object when ever it belong to the + // current likelihood + while (povertyLines.next()) + { + String likelihoodCode = povertyLines.getString("code"); + + if(likelihoodCode.equals(codeName)) + { + povertyLineDatas.add(new PovertyLineData( + povertyLines.getLong("id"), + povertyLines.getLong("score_from"), + povertyLines.getLong("score_to"), + povertyLines.getDouble("poverty_line") + )); + } + } + + povertyLines.beforeFirst(); + + // create the likelihood object with the list of povertyLine object + // belonging to it + + LikeliHoodPovertyLineData likeliHoodPovertyLineData = new LikeliHoodPovertyLineData( + likelihoods.getLong("id"), + povertyLineDatas, + likelihoods.getString("name"), + likelihoods.getString("code"), + likelihoods.getLong("enabled") + ); + + listOfLikeliHoodPovertyLineData.add(likeliHoodPovertyLineData); + + } + + PpiPovertyLineData ppiPovertyLineData = new PpiPovertyLineData(listOfLikeliHoodPovertyLineData,ppiName); + + return ppiPovertyLineData; + } + + @Override + public LikeliHoodPovertyLineData retrieveForLikelihood(final String ppiName, final Long likelihoodId) + { + + final SqlRowSet povertyLines = this._getPovertyLines(likelihoodId); + + List povertyLineDatas = new ArrayList(); + + while (povertyLines.next()) + { + + povertyLineDatas.add(new PovertyLineData( + povertyLines.getLong("id"), + povertyLines.getLong("score_from"), + povertyLines.getLong("score_to"), + povertyLines.getDouble("poverty_line") + )); + } + + povertyLines.first(); + + // create the likelihood object with the list of povertyLine object + // belonging to it + + return new LikeliHoodPovertyLineData( + povertyLines.getLong("likelihood_id"), + povertyLineDatas, + povertyLines.getString("name"), + povertyLines.getString("code"), + povertyLines.getLong("enabled") + ); + + } + + private SqlRowSet _getLikelihoods() + { + String sql = "SELECT lkp.id, lkh.code , lkh.name, lkp.enabled " + + " FROM ppi_likelihoods lkh " + + " JOIN ppi_likelihoods_ppi lkp on lkp.likelihood_id = lkh.id "; + return this.jdbcTemplate.queryForRowSet(sql); + } + + private SqlRowSet _getPovertyLines(final String ppiName) + { + String sql = "SELECT pl.id, sc.score_from, sc.score_to , pl.poverty_line,lkh.code , lkh.name , lkp.ppi_name " + + " FROM ppi_poverty_line pl " + + " JOIN ppi_likelihoods lkh on lkh.id = pl.likelihood_ppi_id " + + " JOIN ppi_likelihoods_ppi lkp on lkp.id = pl.likelihood_ppi_id " + + " JOIN ppi_scores sc on sc.id = pl.score_id " + + " WHERE lkp.ppi_name = ? "; + + return this.jdbcTemplate.queryForRowSet(sql, new Object[] {ppiName}); + + } + + private SqlRowSet _getPovertyLines(final Long likelihoodId) + { + String sql = "SELECT pl.id, sc.score_from, sc.score_to , pl.poverty_line,lkh.code , lkp.enabled, lkp.id as likelihood_id , lkh.name , lkp.ppi_name " + + " FROM ppi_poverty_line pl " + +" JOIN ppi_likelihoods_ppi lkp on lkp.id = pl.likelihood_ppi_id " + +" JOIN ppi_likelihoods lkh on lkh.id = lkp.likelihood_id " + + " JOIN ppi_scores sc on sc.id = pl.score_id " + + " WHERE pl.likelihood_ppi_id = ? "; + + return this.jdbcTemplate.queryForRowSet(sql, new Object[] {likelihoodId}); + + } + + + +// public PovertyLineData retrieve() +// { +// +// } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodService.java new file mode 100644 index 000000000..4f953ed37 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodService.java @@ -0,0 +1,14 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.survey.data.LikelihoodData; + +import java.util.List; + +/** + * Created by Cieyou on 3/12/14. + */ +public interface ReadLikelihoodService { + + public List retrieveAll(final String ppiName); + public LikelihoodData retrieve(final Long likelihoodId); +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodServiceImpl.java new file mode 100644 index 000000000..8b563320f --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadLikelihoodServiceImpl.java @@ -0,0 +1,98 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.core.service.RoutingDataSource; +import org.mifosplatform.infrastructure.survey.data.LikelihoodData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Cieyou on 3/12/14. + */ +@Service +public class ReadLikelihoodServiceImpl implements ReadLikelihoodService { + + private final static Logger logger = LoggerFactory.getLogger(PovertyLineService.class); + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + + @Autowired + ReadLikelihoodServiceImpl(final RoutingDataSource dataSource){ + this.dataSource = dataSource; + this.jdbcTemplate = new JdbcTemplate(this.dataSource); + + } + + @Override + public List retrieveAll(final String ppiName) + { + final SqlRowSet likelihood =this._getLikelihood(ppiName); + + List likelihoodDatas = new ArrayList(); + + while(likelihood.next()) + { + likelihoodDatas.add(new LikelihoodData( + likelihood.getLong("id"), + likelihood.getString("name"), + likelihood.getString("code"), + likelihood.getLong("enabled") + + )); + + } + + + return likelihoodDatas; + } + + private SqlRowSet _getLikelihood(final String ppiName) + { + String sql = "SELECT lkp.id, lkh.code , lkh.name, lkp.enabled " + + " FROM ppi_poverty_line pl " + + " JOIN ppi_likelihoods_ppi lkp on lkp.id = pl.likelihood_ppi_id " + + " JOIN ppi_likelihoods lkh on lkp.likelihood_id = lkh.id " + + " WHERE lkp.ppi_name = ? " + + " GROUP BY pl.likelihood_ppi_id "; + + return this.jdbcTemplate.queryForRowSet(sql, new Object[] {ppiName}); + + } + + @Override + public LikelihoodData retrieve(final Long likelihoodId) + { + final SqlRowSet likelihood =this._getLikelihood(likelihoodId); + + likelihood.first(); + + return new LikelihoodData( + likelihood.getLong("id"), + likelihood.getString("name"), + likelihood.getString("code"), + likelihood.getLong("enabled") + + ); + + } + + private SqlRowSet _getLikelihood(final Long likelihoodId) + { + String sql = "SELECT lkp.id, lkh.code , lkh.name, lkp.enabled " + + " FROM ppi_likelihoods lkh " + + " JOIN ppi_likelihoods_ppi lkp on lkp.likelihood_id = lkh.id " + + " WHERE lkp.id = ? "; + + return this.jdbcTemplate.queryForRowSet(sql, new Object[] {likelihoodId}); + + } + + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java new file mode 100644 index 000000000..94eb87cf7 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java @@ -0,0 +1,25 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; +import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; +import org.mifosplatform.infrastructure.survey.data.ClientScoresOverview; +import org.mifosplatform.infrastructure.survey.data.SurveyDataTableData; + +import java.util.List; + +/** + * Created by Cieyou on 2/27/14. + */ +public interface ReadSurveyService { + + List retrieveAllSurveys(); + + SurveyDataTableData retrieveSurvey(String surveyName); + + ListretrieveClientSurveyScoreOverview(String surveyName, Long clientId); + + GenericResultsetData retrieveSurveyEntry(String surveyName, Long clientId, Long entryId); + +} + + diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java new file mode 100644 index 000000000..595d4a2c2 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java @@ -0,0 +1,162 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.joda.time.LocalDate; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.mifosplatform.infrastructure.core.service.RoutingDataSource; +import org.mifosplatform.infrastructure.dataqueries.api.DataTableApiConstant; +import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; +import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; +import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnHeaderData; +import org.mifosplatform.infrastructure.dataqueries.service.GenericDataService; +import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.infrastructure.survey.data.ClientScoresOverview; +import org.mifosplatform.infrastructure.survey.data.LikelihoodStatus; +import org.mifosplatform.infrastructure.survey.data.SurveyDataTableData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + + +@Service +public class ReadSurveyServiceImpl implements ReadSurveyService { + + private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + private final GenericDataService genericDataService; + private final ReadWriteNonCoreDataService readWriteNonCoreDataService; + private final static Logger logger = LoggerFactory.getLogger(ReadSurveyServiceImpl.class); + + @Autowired + public ReadSurveyServiceImpl(final PlatformSecurityContext context, + final RoutingDataSource dataSource, + final FromJsonHelper fromJsonHelper, + final GenericDataService genericDataService, + final ReadWriteNonCoreDataService readWriteNonCoreDataService){ + + this.context = context; + this.dataSource = dataSource; + this.jdbcTemplate = new JdbcTemplate(this.dataSource); + this.genericDataService = genericDataService; + this.readWriteNonCoreDataService = readWriteNonCoreDataService; + } + + @Override + public List retrieveAllSurveys() + { + + String sql = this.retrieveAllSurveySQL(""); + + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); + + final List surveyDataTables = new ArrayList(); + while (rs.next()) { + final String appTableName = rs.getString("application_table_name"); + final String registeredDatatableName = rs.getString("registered_table_name"); + final boolean enabled = rs.getBoolean("enabled"); + final List columnHeaderData = this.genericDataService + .fillResultsetColumnHeaders(registeredDatatableName); + + surveyDataTables.add( + SurveyDataTableData.create( + DatatableData.create(appTableName, registeredDatatableName, columnHeaderData), + enabled + ) + ); + } + + return surveyDataTables; + } + + private String retrieveAllSurveySQL(String andClause ) + { + // PERMITTED datatables + return "select application_table_name, cf.enabled, registered_table_name" + " from x_registered_table " + + " left join c_configuration cf on x_registered_table.registered_table_name = cf.name " + + " where exists" + + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id" + + " where ur.appuser_id = " + this.context.authenticatedUser().getId() + + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " + + " and x_registered_table.category = "+ DataTableApiConstant.CATEGORY_PPI + + andClause + " order by application_table_name, registered_table_name"; + } + + @Override + public SurveyDataTableData retrieveSurvey(String surveyName) + { + final String sql = "select cf.enabled, application_table_name, registered_table_name" + " from x_registered_table " + + " left join c_configuration cf on x_registered_table.registered_table_name = cf.name " + + " where exists" + + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id" + + " where ur.appuser_id = " + this.context.authenticatedUser().getId() + " and registered_table_name='" + surveyName + "'" + + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " + + " order by application_table_name, registered_table_name"; + + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); + + SurveyDataTableData datatableData = null; + while (rs.next()) { + final String appTableName = rs.getString("application_table_name"); + final String registeredDatatableName = rs.getString("registered_table_name"); + final boolean enabled = rs.getBoolean("enabled"); + final List columnHeaderData = this.genericDataService + .fillResultsetColumnHeaders(registeredDatatableName); + + datatableData = SurveyDataTableData.create( + DatatableData.create(appTableName, registeredDatatableName, columnHeaderData), + enabled + ); + + } + + return datatableData; + } + + public List retrieveClientSurveyScoreOverview(String surveyName, Long clientId) + { + + final String sql = "SELECT tz.id, lkh.name, lkh.code, poverty_line, tz.date, tz.score FROM "+surveyName+" tz" + +" JOIN ppi_likelihoods_ppi lkp on lkp.ppi_name = '"+surveyName+"' AND enabled = '"+ LikelihoodStatus.ENABLED + +"' JOIN ppi_scores sc on score_from <= tz.score AND score_to >=tz.score" + +" JOIN ppi_poverty_line pvl on pvl.likelihood_ppi_id = lkp.id AND pvl.score_id = sc.id" + +" JOIN ppi_likelihoods lkh on lkh.id = lkp.likelihood_id " + +" WHERE client_id = "+clientId; + + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); + + List scoresOverviews = new ArrayList(); + + while(rs.next()) + { + scoresOverviews.add(new ClientScoresOverview( + rs.getString("code"), + rs.getString("name"), + rs.getLong("score"), + rs.getDouble("poverty_line"), + new LocalDate(rs.getTimestamp("date").getTime()), + rs.getLong("id") + )); + } + + + return scoresOverviews ; + } + + public GenericResultsetData retrieveSurveyEntry(String surveyName, Long clientId, Long entryId) + { + + return readWriteNonCoreDataService.retrieveDataTableGenericResultSet(surveyName, clientId, + null, entryId); + + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodService.java new file mode 100644 index 000000000..eff1a7159 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodService.java @@ -0,0 +1,12 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; + +/** + * Created by Cieyou on 3/12/14. + */ +public interface WriteLikelihoodService { + + CommandProcessingResult update(Long likelihoodId, JsonCommand command); +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java new file mode 100644 index 000000000..a41fa8404 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java @@ -0,0 +1,103 @@ +package org.mifosplatform.infrastructure.survey.service; + +import com.google.gson.JsonElement; +import org.mifosplatform.infrastructure.configuration.domain.GlobalConfigurationProperty; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; +import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; +import org.mifosplatform.infrastructure.core.service.RoutingDataSource; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.infrastructure.survey.data.LikelihoodDataValidator; +import org.mifosplatform.infrastructure.survey.data.LikelihoodStatus; +import org.mifosplatform.infrastructure.survey.domain.Likelihood; +import org.mifosplatform.infrastructure.survey.domain.LikelihoodRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; + +/** + * Created by Cieyou on 3/12/14. + */ +@Service +public class WriteLikelihoodServiceImpl implements WriteLikelihoodService{ + + private final static Logger logger = LoggerFactory.getLogger(PovertyLineService.class); + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + private final PlatformSecurityContext context; + private final LikelihoodDataValidator likelihoodDataValidator; + private final LikelihoodRepository repository; + + @Autowired + WriteLikelihoodServiceImpl (final RoutingDataSource dataSource, + final PlatformSecurityContext context, + final LikelihoodDataValidator likelihoodDataValidator, + final LikelihoodRepository repository){ + this.dataSource = dataSource; + this.jdbcTemplate = new JdbcTemplate(this.dataSource); + this.context = context; + this.likelihoodDataValidator = likelihoodDataValidator; + this.repository = repository; + + } + + @Override + public CommandProcessingResult update(Long likelihoodId, JsonCommand command) + { + + this.context.authenticatedUser(); + + try { + + this.likelihoodDataValidator.validateForUpdate(command); + + final Likelihood likelihood = this.repository.findOne(likelihoodId); + + + + String disableLikelihoodSql = "update ppi_likelihoods_ppi set enabled = "+ LikelihoodStatus.DISABLED + + " WHERE ppi_likelihoods_ppi.id IN " + + " ( SELECT t.id FROM ( SELECT * FROM ppi_likelihoods_ppi ) as t " + + " WHERE t.ppi_name = '" + likelihood.getPpiName() + + "' AND t.id !=" +likelihood.getId()+ " ) "; + + + if (!likelihood.update(command).isEmpty()) { + this.repository.save(likelihood); + + if(likelihood.isActivateCommand(command)) + { + // disable the other likelihood + jdbcTemplate.execute(disableLikelihoodSql); + } + + } + + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(likelihood.getId()).build(); + + } catch (final DataIntegrityViolationException dve) { + handleDataIntegrityIssues(dve); + return CommandProcessingResult.empty(); + } + + } + + + /* + * Guaranteed to throw an exception no matter what the data integrity issue + * is. + */ + private void handleDataIntegrityIssues(final DataIntegrityViolationException dve) { + + final Throwable realCause = dve.getMostSpecificCause(); + logger.error(dve.getMessage(), dve); + throw new PlatformDataIntegrityException("error.msg.likelihood.unknown.data.integrity.issue", + "Unknown data integrity issue with resource: " + realCause.getMessage()); + } +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyService.java new file mode 100644 index 000000000..7fcd11de8 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyService.java @@ -0,0 +1,14 @@ +package org.mifosplatform.infrastructure.survey.service; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; + +/** + * Created by Cieyou on 3/13/14. + */ +public interface WriteSurveyService { + + CommandProcessingResult registerSurvey(JsonCommand command); + + CommandProcessingResult fullFillSurvey(String datatable, Long appTableId, JsonCommand command); +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyServiceImpl.java new file mode 100644 index 000000000..90f5a042a --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteSurveyServiceImpl.java @@ -0,0 +1,139 @@ +package org.mifosplatform.infrastructure.survey.service; + +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang.StringUtils; +import org.hibernate.exception.ConstraintViolationException; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; +import org.mifosplatform.infrastructure.core.serialization.DatatableCommandFromApiJsonDeserializer; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.mifosplatform.infrastructure.core.serialization.JsonParserHelper; +import org.mifosplatform.infrastructure.core.service.RoutingDataSource; +import org.mifosplatform.infrastructure.dataqueries.data.DataTableValidator; +import org.mifosplatform.infrastructure.dataqueries.data.ResultsetColumnHeaderData; +import org.mifosplatform.infrastructure.dataqueries.service.GenericDataService; +import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.sql.DataSource; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +/** + * Created by Cieyou on 3/13/14. + */ +@Service +public class WriteSurveyServiceImpl implements WriteSurveyService { + + private final static Logger logger = LoggerFactory.getLogger(PovertyLineService.class); + + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + private final PlatformSecurityContext context; + private final FromJsonHelper fromJsonHelper; + private final JsonParserHelper helper; + private final GenericDataService genericDataService; + private final DatatableCommandFromApiJsonDeserializer fromApiJsonDeserializer; + private final DataTableValidator dataTableValidator; + private final ReadWriteNonCoreDataService readWriteNonCoreDataService; + + @Autowired(required = true) + WriteSurveyServiceImpl(final RoutingDataSource dataSource, + final PlatformSecurityContext context, + final FromJsonHelper fromJsonHelper, + final GenericDataService genericDataService, + final DatatableCommandFromApiJsonDeserializer fromApiJsonDeserializer, + final DataTableValidator dataTableValidator, + final ReadWriteNonCoreDataService readWriteNonCoreDataService) { + this.dataSource = dataSource; + this.jdbcTemplate = new JdbcTemplate(this.dataSource); + this.context = context; + this.fromJsonHelper = fromJsonHelper; + this.helper = new JsonParserHelper(); + this.genericDataService = genericDataService; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; + this.dataTableValidator = dataTableValidator; + this.readWriteNonCoreDataService = readWriteNonCoreDataService; + + } + + + @Override + @Transactional + public CommandProcessingResult registerSurvey(JsonCommand command) + { + + final String dataTableName = this.readWriteNonCoreDataService.getDataTableName(command.getUrl()); + final String permissionSql = this._getPermissionSql(dataTableName); + this.readWriteNonCoreDataService.registerDatatable(command, permissionSql); + + return CommandProcessingResult.commandOnlyResult(command.commandId()); + + } + + private String _getPermissionSql(final String dataTableName) + { + final String createPermission = "'CREATE_" + dataTableName + "'"; + final String createPermissionChecker = "'CREATE_" + dataTableName + "_CHECKER'"; + final String readPermission = "'READ_" + dataTableName + "'"; + final String updatePermission = "'UPDATE_" + dataTableName + "'"; + final String updatePermissionChecker = "'UPDATE_" + dataTableName + "_CHECKER'"; + final String deletePermission = "'DELETE_" + dataTableName + "'"; + final String deletePermissionChecker = "'DELETE_" + dataTableName + "_CHECKER'"; + + return "insert into m_permission (grouping, code, action_name, entity_name, can_maker_checker) values " + + "('datatable', " + + createPermission + + ", 'CREATE', '" + + dataTableName + + "', false)," + + "('datatable', " + + createPermissionChecker + + ", 'CREATE', '" + + dataTableName + + "', false)," + + "('datatable', " + + readPermission + + ", 'READ', '" + + dataTableName + + "', false)," + + "('datatable', " + + updatePermission + + ", 'UPDATE', '" + + dataTableName + + "', false)," + + "('datatable', " + + updatePermissionChecker + + ", 'UPDATE', '" + + dataTableName + + "', false)," + + "('datatable', " + + deletePermission + + ", 'DELETE', '" + + dataTableName + + "', false)," + + "('datatable', " + + deletePermissionChecker + + ", 'DELETE', '" + + dataTableName + "', false)"; + } + + @Transactional + @Override + public CommandProcessingResult fullFillSurvey(final String dataTableName, final Long appTableId, final JsonCommand command) { + + return readWriteNonCoreDataService.createPPIEntry(dataTableName,appTableId,command); + } + + +} From c1acf1baae598e7590dc3fa4b6da44c326c4f7bb Mon Sep 17 00:00:00 2001 From: CieyouRaoul Date: Thu, 10 Apr 2014 12:22:40 +0200 Subject: [PATCH 2/4] modified the ppi call to retrieve ppi entry. instead of returning the entry of the active ppi now return all the entries of a user --- .../survey/api/SurveyApiResource.java | 16 ++++- .../survey/data/ClientScoresOverview.java | 5 +- .../survey/service/ReadSurveyService.java | 1 + .../survey/service/ReadSurveyServiceImpl.java | 62 ++++++++++++++++++- 4 files changed, 80 insertions(+), 4 deletions(-) diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java index f20b4d1e7..9c86440e1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java @@ -121,11 +121,25 @@ public class SurveyApiResource { this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); - List scores = this.readSurveyService.retrieveClientSurveyScoreOverview(surveyName, clientId); + List scores = this.readSurveyService.retrieveClientSurveyScoreOverview(clientId); return this.toApiJsonClientScoreOverviewSerializer.serialize(scores); } +// @GET +// @Path("{clientId}") +// @Consumes({ MediaType.APPLICATION_JSON }) +// @Produces({ MediaType.APPLICATION_JSON }) +// public String getAllClientSurveyOverview( @PathParam("clientId") final Long clientId) { +// +// +// this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); +// +// List scores = this.readSurveyService.retrieveClientSurveyScoreOverview(clientId); +// +// return this.toApiJsonClientScoreOverviewSerializer.serialize(scores); +// } + @GET @Path("{surveyName}/{clientId}/{entryId}") @Consumes({ MediaType.APPLICATION_JSON }) diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java index 43a1a5138..7f8618fc3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/data/ClientScoresOverview.java @@ -7,6 +7,7 @@ import org.joda.time.LocalDate; */ public class ClientScoresOverview { + final private String surveyName; final private long id ; final private String likelihoodCode ; final private String likelihoodName; @@ -19,7 +20,8 @@ public class ClientScoresOverview { final long score, final Double povertyLine, final LocalDate date, - final long resourceId) { + final long resourceId, + final String surveyName) { this.likelihoodCode = likelihoodCode; this.likelihoodName = likelihoodName; @@ -27,6 +29,7 @@ public class ClientScoresOverview { this.povertyLine = povertyLine; this.date = date; this.id = resourceId; + this.surveyName = surveyName; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java index 94eb87cf7..54940b617 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyService.java @@ -17,6 +17,7 @@ public interface ReadSurveyService { SurveyDataTableData retrieveSurvey(String surveyName); ListretrieveClientSurveyScoreOverview(String surveyName, Long clientId); + ListretrieveClientSurveyScoreOverview(Long clientId); GenericResultsetData retrieveSurveyEntry(String surveyName, Long clientId, Long entryId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java index 595d4a2c2..e8121654a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/ReadSurveyServiceImpl.java @@ -125,7 +125,7 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { public List retrieveClientSurveyScoreOverview(String surveyName, Long clientId) { - final String sql = "SELECT tz.id, lkh.name, lkh.code, poverty_line, tz.date, tz.score FROM "+surveyName+" tz" + final String sql = "SELECT tz.id, lkh.name, lkh.code, poverty_line, tz.date, tz.score FROM "+surveyName+" tz" +" JOIN ppi_likelihoods_ppi lkp on lkp.ppi_name = '"+surveyName+"' AND enabled = '"+ LikelihoodStatus.ENABLED +"' JOIN ppi_scores sc on score_from <= tz.score AND score_to >=tz.score" +" JOIN ppi_poverty_line pvl on pvl.likelihood_ppi_id = lkp.id AND pvl.score_id = sc.id" @@ -144,7 +144,8 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { rs.getLong("score"), rs.getDouble("poverty_line"), new LocalDate(rs.getTimestamp("date").getTime()), - rs.getLong("id") + rs.getLong("id"), + surveyName )); } @@ -152,6 +153,63 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { return scoresOverviews ; } + public List retrieveClientSurveyScoreOverview(Long clientId) + { + final String surveyNameSql = retrieveAllSurveyNameSQL(); + final SqlRowSet surveyNames = this.jdbcTemplate.queryForRowSet(surveyNameSql); + + ArrayList sqls = new ArrayList(); + + while(surveyNames .next()) + { + sqls.add( "SELECT '"+surveyNames.getString("name") +"' as surveyName, tz.id, lkh.name, lkh.code, poverty_line, tz.date, tz.score FROM "+surveyNames.getString("name")+" tz" + +" JOIN ppi_likelihoods_ppi lkp on lkp.ppi_name = '"+surveyNames.getString("name")+"' AND enabled = '"+ LikelihoodStatus.ENABLED + +"' JOIN ppi_scores sc on score_from <= tz.score AND score_to >=tz.score" + +" JOIN ppi_poverty_line pvl on pvl.likelihood_ppi_id = lkp.id AND pvl.score_id = sc.id" + +" JOIN ppi_likelihoods lkh on lkh.id = lkp.likelihood_id " + +" WHERE client_id = "+clientId ); + } + + List scoresOverviews = new ArrayList(); + + for(String sql:sqls) + { + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); + + + + while(rs.next()) + { + scoresOverviews.add(new ClientScoresOverview( + rs.getString("code"), + rs.getString("name"), + rs.getLong("score"), + rs.getDouble("poverty_line"), + new LocalDate(rs.getTimestamp("date").getTime()), + rs.getLong("id"), + rs.getString("surveyName") + )); + } + + } + + return scoresOverviews ; + } + + private String retrieveAllSurveyNameSQL() + { + // PERMITTED datatables + return "select cf.name from x_registered_table " + + " join c_configuration cf on x_registered_table.registered_table_name = cf.name " + + " where exists" + + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id" + + " where ur.appuser_id = " + this.context.authenticatedUser().getId() + + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " + + " and x_registered_table.category = "+ DataTableApiConstant.CATEGORY_PPI + + " order by application_table_name, registered_table_name"; + } + public GenericResultsetData retrieveSurveyEntry(String surveyName, Long clientId, Long entryId) { From 712b5e000cb876e574cd88fe9b7c4993cd98db23 Mon Sep 17 00:00:00 2001 From: CieyouRaoul Date: Thu, 15 May 2014 13:32:24 +0200 Subject: [PATCH 3/4] implement jpa for likelihood write operation, set default value for registered table category, add likelihood table sql --- .../V148__x_registered_table_category.sql | 2 +- .../core_db/V150_2__likelihood_table.sql | 89 ++++++++++++++ .../SurveyIntegrationTest.java | 112 ++++++++++++++++++ ...obalConfigurationWritePlatformService.java | 1 - ...WritePlatformServiceJpaRepositoryImpl.java | 23 ---- .../survey/api/LikelihoodApiResource.java | 2 +- .../survey/api/SurveyApiResource.java | 13 -- .../survey/domain/Likelihood.java | 5 + .../survey/domain/LikelihoodRepository.java | 8 +- .../service/WriteLikelihoodServiceImpl.java | 18 ++- 10 files changed, 221 insertions(+), 52 deletions(-) create mode 100644 mifosng-db/migrations/core_db/V150_2__likelihood_table.sql create mode 100644 mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/SurveyIntegrationTest.java diff --git a/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql b/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql index 88903f444..dcbac2150 100644 --- a/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql +++ b/mifosng-db/migrations/core_db/V148__x_registered_table_category.sql @@ -1 +1 @@ -ALTER TABLE `x_registered_table` ADD `category` INT NOT NULL ; \ No newline at end of file +ALTER TABLE `x_registered_table` ADD `category` INT NOT NULL DEFAULT(100); \ No newline at end of file diff --git a/mifosng-db/migrations/core_db/V150_2__likelihood_table.sql b/mifosng-db/migrations/core_db/V150_2__likelihood_table.sql new file mode 100644 index 000000000..493e985c9 --- /dev/null +++ b/mifosng-db/migrations/core_db/V150_2__likelihood_table.sql @@ -0,0 +1,89 @@ +-- +--CREATE TABLE IF NOT EXISTS `ppi_scores` ( +-- `id` int(11) NOT NULL AUTO_INCREMENT, +-- `score_from` int(11) NOT NULL, +-- `score_to` int(11) NOT NULL, +-- PRIMARY KEY (`id`) +--) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; +-- +-- +--INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (0, 4); +-- +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (5, 9); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (10, 14); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (15, 19); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (20, 24); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (25,29 ); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (30, 34); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (35, 39); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (40, 44); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (45, 49); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (50, 54); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (55, 59); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (60,64); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (65, 69); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (70, 74); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (75, 79); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (80,84); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (85, 89); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (90, 94); +-- INSERT INTO `ppi_scores` ( `score_from`, `score_to`) +--VALUES +-- (95, 100); +-- +-- -- likelihood table +-- +-- CREATE TABLE IF NOT EXISTS `ppi_likelihoods` ( +-- `id` bigint(20) NOT NULL AUTO_INCREMENT, +-- `code` varchar(100) NOT NULL, +-- `name` varchar(250) NOT NULL, +-- PRIMARY KEY (`id`) +--) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; +-- +-- +-- +-- CREATE TABLE IF NOT EXISTS `ppi_likelihoods_ppi` ( +-- `id` bigint(20) NOT NULL AUTO_INCREMENT, +-- `likelihood_id` bigint(20) NOT NULL, +-- `ppi_name` varchar(250) NOT NULL, +-- `enabled` int(11) NOT NULL DEFAULT '100', +-- PRIMARY KEY (`id`) +--) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; \ No newline at end of file diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/SurveyIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/SurveyIntegrationTest.java new file mode 100644 index 000000000..f813b2dd4 --- /dev/null +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/SurveyIntegrationTest.java @@ -0,0 +1,112 @@ +package org.mifosplatform.integrationtests; + +import com.jayway.restassured.builder.RequestSpecBuilder; +import com.jayway.restassured.builder.ResponseSpecBuilder; +import com.jayway.restassured.http.ContentType; +import com.jayway.restassured.specification.RequestSpecification; +import com.jayway.restassured.specification.ResponseSpecification; +import org.junit.Before; +import org.junit.Test; +import org.mifosplatform.integrationtests.common.ClientHelper; +import org.mifosplatform.integrationtests.common.Utils; +import org.mifosplatform.integrationtests.common.loans.LoanApplicationTestBuilder; +import org.mifosplatform.integrationtests.common.loans.LoanProductTestBuilder; +import org.mifosplatform.integrationtests.common.loans.LoanTransactionHelper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; + +/** + * Client Loan Integration Test for checking Loan Application Repayment + * Schedule. + */ +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class SurveyIntegrationTest { + + private ResponseSpecification responseSpec; + private RequestSpecification requestSpec; + private LoanTransactionHelper loanTransactionHelper; + + @Before + public 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(); + } + + @Test + public void checkClientLoanCreateAndDisburseFlow() { + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); + final Integer loanProductID = createLoanProduct(); + final Integer loanID = applyForLoanApplication(clientID, loanProductID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); + verifyLoanRepaymentSchedule(loanSchedule); + + } + + private Integer createLoanProduct() { + System.out.println("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); + final String loanProductJSON = new LoanProductTestBuilder() // + .withPrincipal("12,000.00") // + .withNumberOfRepayments("4") // + .withRepaymentAfterEvery("1") // + .withRepaymentTypeAsMonth() // + .withinterestRatePerPeriod("1") // + .withInterestRateFrequencyTypeAsMonths() // + .withAmortizationTypeAsEqualInstallments() // + .withInterestTypeAsDecliningBalance() // + .build(); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); + } + + private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID) { + System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); + final String loanApplicationJSON = new LoanApplicationTestBuilder() // + .withPrincipal("12,000.00") // + .withLoanTermFrequency("4") // + .withLoanTermFrequencyAsMonths() // + .withNumberOfRepayments("4") // + .withRepaymentEveryAfter("1") // + .withRepaymentFrequencyTypeAsMonths() // + .withInterestRatePerPeriod("2") // + .withAmortizationTypeAsEqualInstallments() // + .withInterestTypeAsDecliningBalance() // + .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // + .withExpectedDisbursementDate("20 September 2011") // + .withSubmittedOnDate("20 September 2011") // + .build(clientID.toString(), loanProductID.toString()); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); + } + + private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule) { + System.out.println("--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); + + assertEquals("Checking for Due Date for 1st Month", new ArrayList(Arrays.asList(2011, 10, 20)), + loanSchedule.get(1).get("dueDate")); + assertEquals("Checking for Principal Due for 1st Month", new Float("2911.49"), loanSchedule.get(1).get("principalOriginalDue")); + assertEquals("Checking for Interest Due for 1st Month", new Float("240.00"), loanSchedule.get(1).get("interestOriginalDue")); + + assertEquals("Checking for Due Date for 2nd Month", new ArrayList(Arrays.asList(2011, 11, 20)), + loanSchedule.get(2).get("dueDate")); + assertEquals("Checking for Principal Due for 2nd Month", new Float("2969.71"), loanSchedule.get(2).get("principalDue")); + assertEquals("Checking for Interest Due for 2nd Month", new Float("181.77"), loanSchedule.get(2).get("interestOriginalDue")); + + assertEquals("Checking for Due Date for 3rd Month", new ArrayList(Arrays.asList(2011, 12, 20)), + loanSchedule.get(3).get("dueDate")); + assertEquals("Checking for Principal Due for 3rd Month", new Float("3029.1"), loanSchedule.get(3).get("principalDue")); + assertEquals("Checking for Interest Due for 3rd Month", new Float("122.38"), loanSchedule.get(3).get("interestOriginalDue")); + + assertEquals("Checking for Due Date for 4th Month", new ArrayList(Arrays.asList(2012, 1, 20)), + loanSchedule.get(4).get("dueDate")); + assertEquals("Checking for Principal Due for 4th Month", new Float("3089.7"), loanSchedule.get(4).get("principalDue")); + assertEquals("Checking for Interest Due for 4th Month", new Float("61.79"), loanSchedule.get(4).get("interestOriginalDue")); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java index fea85b3dd..95fa15d0a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java @@ -11,6 +11,5 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; public interface GlobalConfigurationWritePlatformService { CommandProcessingResult update(Long configId, JsonCommand command); - CommandProcessingResult update(String name, JsonCommand command); void addSurveyConfig(String name); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java index ad64270de..ca3e6b950 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java @@ -66,29 +66,6 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements } - @Transactional - @Override - public CommandProcessingResult update(final String name, final JsonCommand command) { - - this.context.authenticatedUser(); - - try { - this.globalConfigurationDataValidator.validateForUpdate(command); - - final GlobalConfigurationProperty configItemForUpdate = this.repository.findOneByNameWithNotFoundDetection(name); - - if (configItemForUpdate.updateTo(true)) { - this.repository.save(configItemForUpdate); - } - - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(configItemForUpdate.getId()).build(); - - } catch (final DataIntegrityViolationException dve) { - handleDataIntegrityIssues(dve); - return CommandProcessingResult.empty(); - } - - } @Transactional @Override diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java index 00ebd9f2f..8f887b205 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/LikelihoodApiResource.java @@ -75,7 +75,7 @@ public class LikelihoodApiResource { } @PUT - @Path("{likelihoodId}") + @Path("{ppiName}/{likelihoodId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String update(@PathParam("likelihoodId") final Long likelihoodId, final String apiRequestBodyAsJson){ diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java index 9c86440e1..c75c5eb48 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/api/SurveyApiResource.java @@ -126,19 +126,6 @@ public class SurveyApiResource { return this.toApiJsonClientScoreOverviewSerializer.serialize(scores); } -// @GET -// @Path("{clientId}") -// @Consumes({ MediaType.APPLICATION_JSON }) -// @Produces({ MediaType.APPLICATION_JSON }) -// public String getAllClientSurveyOverview( @PathParam("clientId") final Long clientId) { -// -// -// this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); -// -// List scores = this.readSurveyService.retrieveClientSurveyScoreOverview(clientId); -// -// return this.toApiJsonClientScoreOverviewSerializer.serialize(scores); -// } @GET @Path("{surveyName}/{clientId}/{entryId}") diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java index 0eeb646ce..f1ddb4969 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/Likelihood.java @@ -65,4 +65,9 @@ public final class Likelihood extends AbstractPersistable { public Long getId() { return super.getId(); } + + public void disable() + { + this.enabled = LikelihoodStatus.DISABLED; + } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java index ac0dd02fa..2e252a851 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/domain/LikelihoodRepository.java @@ -3,13 +3,15 @@ package org.mifosplatform.infrastructure.survey.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.util.List; -/** - * Created by Cieyou on 3/12/14. - */ + public interface LikelihoodRepository extends JpaRepository, JpaSpecificationExecutor { + @Query("FROM Likelihood WHERE ppi_name =:ppiName AND id !=:id") + List findByPpiNameAndLikeliHoodId(@Param("ppiName") String ppiName,@Param("id") Long likeliHoodId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java index a41fa8404..113eaff11 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/survey/service/WriteLikelihoodServiceImpl.java @@ -20,6 +20,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import javax.sql.DataSource; +import java.util.List; /** * Created by Cieyou on 3/12/14. @@ -60,21 +61,18 @@ public class WriteLikelihoodServiceImpl implements WriteLikelihoodService{ final Likelihood likelihood = this.repository.findOne(likelihoodId); - - String disableLikelihoodSql = "update ppi_likelihoods_ppi set enabled = "+ LikelihoodStatus.DISABLED - + " WHERE ppi_likelihoods_ppi.id IN " - + " ( SELECT t.id FROM ( SELECT * FROM ppi_likelihoods_ppi ) as t " + - " WHERE t.ppi_name = '" + likelihood.getPpiName() - + "' AND t.id !=" +likelihood.getId()+ " ) "; - - if (!likelihood.update(command).isEmpty()) { this.repository.save(likelihood); if(likelihood.isActivateCommand(command)) { - // disable the other likelihood - jdbcTemplate.execute(disableLikelihoodSql); + List likelihoods = this.repository.findByPpiNameAndLikeliHoodId(likelihood.getPpiName(),likelihood.getId()); + + for(Likelihood aLikelihood:likelihoods) + { + aLikelihood.disable(); + } + this.repository.save(likelihoods); } } From 1ca510b0ca6bde3705811e03756fe23f56b00042 Mon Sep 17 00:00:00 2001 From: CieyouRaoul Date: Tue, 20 May 2014 10:08:54 +0200 Subject: [PATCH 4/4] work in porgress integration test --- .../integrationtests/common/surveyHelper.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/surveyHelper.java diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/surveyHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/surveyHelper.java new file mode 100644 index 000000000..1d7b69a35 --- /dev/null +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/surveyHelper.java @@ -0,0 +1,56 @@ +package org.mifosplatform.integrationtests.common; + +import com.google.gson.Gson; +import com.jayway.restassured.specification.RequestSpecification; +import com.jayway.restassured.specification.ResponseSpecification; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; + +public class surveyHelper { + + private static final String FULFIL_SURVEY_URL = "/mifosng-provider/api/v1/survey/ppi_kenya_2009/clientId?tenantIdentifier=default"; + + public static Integer fulfilSurvey(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + return fulfilSurvey(requestSpec, responseSpec, "04 March 2011"); + } + + public static Integer fulfilSurvey(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String activationDate) { + System.out.println("---------------------------------FULFIL PPI ---------------------------------------------"); + return Utils.performServerPost(requestSpec, responseSpec,FULFIL_SURVEY_URL, getTestPPIAsJSON(), "clientId"); + } + + public static String getTestPPIAsJSON() { + final HashMap map = new HashMap(); + + map.put("date", "2014-05-19 00:00:00"); + map.put("ppi_household_members_cd_q1_householdmembers","107"); + map.put("ppi_highestschool_cd_q2_highestschool","112"); + map.put("ppi_businessoccupation_cd_q3_businessoccupation","116"); + 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"); + map.put("ppi_mosquitonets_cd_q8_mosquitonets", "132"); + map.put("ppi_towels_cd_q9_towels", "134"); + map.put("ppi_fryingpans_cd_q10_fryingpans", "138"); + + System.out.println("map : " + map); + return new Gson().toJson(map); + } + + public static void verifySurveyCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer generatedClientID) { + System.out.println("------------------------------CHECK CLIENT DETAILS------------------------------------\n"); + final String SURVEY_URL = "/mifosng-provider/api/v1/Survey/ppi_kenya_2009/clientid/entryId" + generatedClientID + "?tenantIdentifier=default"; + final Integer responseClientID = Utils.performServerGet(requestSpec, responseSpec, SURVEY_URL, "id"); + assertEquals("ERROR IN CREATING THE CLIENT", generatedClientID, responseClientID); + } + + +} \ No newline at end of file