MIFOSX-merging musonis work around ppi

This commit is contained in:
Vishwas Babu A J
2014-06-05 21:06:30 -07:00
52 changed files with 2781 additions and 76 deletions
+324 -1
View File
@@ -2149,6 +2149,30 @@
<td></td>
<td></td>
</tr>
<tr>
<td><a href="#survey_retrieve">Survey</a></td>
<td>survey/</td>
<td></td>
<td><a href="#survey_retrieve">List surveys</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>survey/{surveyName}</td>
<td></td>
<td><a href="#survey_details">Retrieve Survey details</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>survey/{surveyName}/{clientId}</td>
<td><a href="#survey_create">Create Entry in the survey table</a></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
@@ -11905,6 +11929,39 @@ GET https://DomainName/api/v1/configurations/1
</div>
</div>
<a id="configs_globalconfig_retrieve_survey" name="configs_globalconfig_retrieve_survey" class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h4>Retrieve Global Configuration for surveys</h4>
<p>Returns the list global enable/disable survey configurations.</p>
<p>Example Requests:</p>
<div class=apiClick>configurations/survey</div>
</div>
<div class="method-example">
<code class="method-declaration">
GET https://DomainName/api/v1/configurations/survey
</code>
<code class="method-response">
{
"ppi_kenya_2005": [
{
"name": "maker-checker",
"enabled": true,
"value": 0,
"id": 1
},
{
"name": "ppi_tanzania_20012",
"enabled": false,
"value": 0,
"id": 2
},
]
}
</code>
</div>
</div>
<a id="configs_globalconfig_update" name="configs_globalconfig_update" class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
@@ -24619,7 +24676,10 @@ No Request Body
<h4>Register Data Table</h4>
<p>Registers a data table with the Mifos X Core application
table. This allows the data table to be maintained through the
API.</p>
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)
</p>
</div>
<div class="method-example">
<code class="method-declaration">
@@ -24984,6 +25044,261 @@ Request Body:
</div>
</div>
<!-- end of datatables api docs -->
<!-- start of survey api docs -->
<a id="survey_retrieve" name="survey_retrieve"
class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h4>Retreive surveys</h4>
<p>Retrieve surveys. This allows to retrieve the list of survey tables registered .
</p>
</div>
<div class="method-example">
<code class="method-declaration">
GET https://DomainName/api/v1/survey/
</code>
<code class="method-request">
GET survey/
Content-Type: application/json
Request Body:
{}
</code>
<code class="method-response">
[
{
"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
}
]
</code>
</div>
</div>
<a id="survey_details" name="survey_details"
class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h4>Retreive survey</h4>
<p>Lists a registered survey table details and the Mifos X Core application table they are registered to.
</p>
</div>
<div class="method-example">
<code class="method-declaration">
GET https://DomainName/api/v1/survey/ppi_kenya_2005
</code>
<code class="method-request">
GET survey/{surveyName}
Content-Type: application/json
Request Body:
{}
</code>
<code class="method-response">
{
"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
]
}
</code>
</div>
</div>
<a id="survey_create" name="survey_create"
class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h4>Create an entry in the survey table</h4>
<p>Insert and entry in a survey table (full fill the survey).
</p>
</div>
<div class="method-example">
<code class="method-declaration">
POST https://DomainName/api/v1/survey/ppi_kenya_2005/87
</code>
<code class="method-request">
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"
}
</code>
<code class="method-response">
{
"officeId": 2,
"clientId": 87,
"resourceId": 87
}
</code>
</div>
</div>
<!-- end of Survey api docs -->
<!-- start of Notes api docs -->
<a id="notes" name="notes" class="old-syle-anchor">&nbsp;</a>
@@ -30739,6 +31054,14 @@ No Request Body:
<td><a href="#configs_globalconfig_update">Update Global Configuration</a></td>
<td></td>
</tr>
<tr class="alt">
<td></td>
<td></td>
<td></td>
<td><a href="#configs_globalconfig_retrieve_survey">Retrieve Surveys Global Configuration</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="#configs_codes">Codes</a></td>
<td>codes</td>
+103
View File
@@ -0,0 +1,103 @@
ALTER TABLE `m_code_value`
ADD COLUMN `code_score` INT(11) NULL AFTER `order_position`;
CREATE TABLE IF NOT EXISTS `ppi_scores` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`score_from` int(11) NOT NULL,
`score_to` int(11) NOT NULL,
PRIMARY KEY (`id`)
) COLLATE='utf8_general_ci'
ENGINE=InnoDB;
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);
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`)
) COLLATE='utf8_general_ci'
ENGINE=InnoDB ;
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`)
) COLLATE='utf8_general_ci'
ENGINE=InnoDB;
/**PPI permission**/
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');
/**Registered table category**/
ALTER TABLE `x_registered_table` ADD `category` INT NOT NULL DEFAULT 100;
@@ -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<HashMap> 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<HashMap> loanSchedule) {
System.out.println("--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------");
assertEquals("Checking for Due Date for 1st Month", new ArrayList<Integer>(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<Integer>(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<Integer>(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<Integer>(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"));
}
}
@@ -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<String, String> map = new HashMap<String, String>();
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);
}
}
@@ -5,7 +5,6 @@
*/
package org.mifosplatform.commands.domain;
public class CommandWrapper {
private final Long commandId;
@@ -838,4 +837,31 @@ public class CommandWrapper {
public boolean isOfficeToGLAccountMapping() {
return this.entityName.equalsIgnoreCase("OFFICEGLACCOUNT");
}
public boolean isRegisterDatatable() {
return this.actionName.equalsIgnoreCase("REGISTER") && this.href.startsWith("/datatables/") && this.entityId == null;
}
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");
}
}
@@ -26,8 +26,7 @@ public class CommandWrapperBuilder {
public CommandWrapper build() {
return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, this.actionName,
this.entityName, this.entityId, this.subentityId, this.href, this.json, this.transactionId, this.productId,
this.templateId);
this.entityName, this.entityId, this.subentityId, this.href, this.json, this.transactionId, this.productId, this.templateId);
}
public CommandWrapperBuilder withLoanId(final Long withLoanId) {
@@ -1182,7 +1181,7 @@ public class CommandWrapperBuilder {
this.actionName = "CREATE";
this.entityName = "CHARTSLAB";
this.entityId = null;
this.subentityId = chartId; //refer to chart id
this.subentityId = chartId; // refer to chart id
this.href = "/interestratechart/" + chartId + "/chartdetails/template";
return this;
}
@@ -1191,7 +1190,7 @@ public class CommandWrapperBuilder {
this.actionName = "UPDATE";
this.entityName = "CHARTSLAB";
this.entityId = chartSlabId;
this.subentityId = chartId;//refers parent chart
this.subentityId = chartId;// refers parent chart
this.href = "/interestratechart/" + chartId + "/chartdetails/" + chartSlabId;
return this;
}
@@ -1200,7 +1199,7 @@ public class CommandWrapperBuilder {
this.actionName = "DELETE";
this.entityName = "CHARTSLAB";
this.entityId = chartSlabId;
this.subentityId = chartId;//refers parent chart
this.subentityId = chartId;// refers parent chart
this.href = "/interestratechart/" + chartId + "/chartdetails/" + chartSlabId;
return this;
}
@@ -1983,4 +1982,36 @@ public class CommandWrapperBuilder {
return this;
}
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 updateLikelihood(final Long entityId) {
this.actionName = "UPDATE";
this.entityName = "LIKELIHOOD";
this.href = "/likelihood/" + entityId;
this.entityId = entityId;
return this;
}
}
@@ -5,6 +5,8 @@
*/
package org.mifosplatform.commands.service;
import java.util.Map;
import org.joda.time.DateTime;
import org.mifosplatform.commands.domain.CommandSource;
import org.mifosplatform.commands.domain.CommandSourceRepository;
@@ -24,8 +26,6 @@ import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
@Service
public class SynchronousCommandProcessingService implements CommandProcessingService {
@@ -143,6 +143,8 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = this.applicationContext.getBean("deleteOneToManyDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDeleteOneToOne()) {
handler = this.applicationContext.getBean("deleteOneToOneDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isRegisterDatatable()) {
handler = this.applicationContext.getBean("registerDatatableCommandHandler", NewCommandSourceHandler.class);
} else {
throw new UnsupportedCommandException(wrapper.commandName());
}
@@ -507,7 +509,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
if (wrapper.isCreate()) {
handler = this.applicationContext.getBean("fixedDepositAccountApplicationSubmittalCommandHandler",
NewCommandSourceHandler.class);
}else if (wrapper.isUpdate()) {
} else if (wrapper.isUpdate()) {
handler = this.applicationContext.getBean("fixedDepositAccountApplicationModificationCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isDelete()) {
@@ -519,8 +521,9 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else if (wrapper.isWithdrawFixedDepositAccountApplicationByApplicant()) {
handler = this.applicationContext.getBean("fixedDepositAccountApplicationWithdrawnByApplicantCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isApprovalOfFixedDepositAccountApplication()) {
handler = this.applicationContext.getBean("fixedDepositAccountApplicationApprovalCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isApprovalOfFixedDepositAccountApplication()) {
handler = this.applicationContext.getBean("fixedDepositAccountApplicationApprovalCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isUndoApprovalOfFixedDepositAccountApplication()) {
handler = this.applicationContext.getBean("fixedDepositAccountApplicationApprovalUndoCommandHandler",
NewCommandSourceHandler.class);
@@ -531,11 +534,13 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else if (wrapper.isActivation()) {
handler = this.applicationContext.getBean("activateFixedDepositAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isInterestCalculation()) {
handler = this.applicationContext.getBean("calculateInterestFixedDepositAccountCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("calculateInterestFixedDepositAccountCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isInterestPosting()) {
handler = this.applicationContext.getBean("postInterestFixedDepositAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUndoTransaction()) {
handler = this.applicationContext.getBean("undoTransactionFixedDepositAccountCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext
.getBean("undoTransactionFixedDepositAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isAdjustTransaction()) {
handler = this.applicationContext.getBean("fixedDepositTransactionAdjustmentCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDepositAccountClose()) {
@@ -549,7 +554,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
if (wrapper.isCreate()) {
handler = this.applicationContext.getBean("recurringDepositAccountApplicationSubmittalCommandHandler",
NewCommandSourceHandler.class);
}else if (wrapper.isUpdate()) {
} else if (wrapper.isUpdate()) {
handler = this.applicationContext.getBean("recurringDepositAccountApplicationModificationCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isDelete()) {
@@ -562,7 +567,8 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = this.applicationContext.getBean("recurringDepositAccountApplicationWithdrawnByApplicantCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isApprovalOfRecurringDepositAccountApplication()) {
handler = this.applicationContext.getBean("recurringDepositAccountApplicationApprovalCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("recurringDepositAccountApplicationApprovalCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isUndoApprovalOfRecurringDepositAccountApplication()) {
handler = this.applicationContext.getBean("recurringDepositAccountApplicationApprovalUndoCommandHandler",
NewCommandSourceHandler.class);
@@ -573,17 +579,22 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else if (wrapper.isActivation()) {
handler = this.applicationContext.getBean("activateRecurringDepositAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isInterestCalculation()) {
handler = this.applicationContext.getBean("calculateInterestRecurringDepositAccountCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("calculateInterestRecurringDepositAccountCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isInterestPosting()) {
handler = this.applicationContext.getBean("postInterestRecurringDepositAccountCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("postInterestRecurringDepositAccountCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isUndoTransaction()) {
handler = this.applicationContext.getBean("undoTransactionRecurringDepositAccountCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("undoTransactionRecurringDepositAccountCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isAdjustTransaction()) {
handler = this.applicationContext.getBean("recurringDepositTransactionAdjustmentCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("recurringDepositTransactionAdjustmentCommandHandler",
NewCommandSourceHandler.class);
} else if (wrapper.isDepositAccountClose()) {
handler = this.applicationContext.getBean("closeRecurringDepositAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDepositAccountPrematureClose()) {
handler = this.applicationContext.getBean("prematureCloseRecurringDepositAccountCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("prematureCloseRecurringDepositAccountCommandHandler",
NewCommandSourceHandler.class);
} else {
throw new UnsupportedCommandException(wrapper.commandName());
}
@@ -787,6 +798,20 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else {
throw new UnsupportedCommandException(wrapper.commandName());
}
} 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());
@@ -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;
@@ -68,11 +63,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);
@@ -76,4 +76,9 @@ public class GlobalConfigurationProperty extends AbstractPersistable<Long> {
}
public static GlobalConfigurationProperty newSurveyConfiguration(final String name)
{
return new GlobalConfigurationProperty(name,false,null);
}
}
@@ -10,8 +10,8 @@ import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationPr
public interface ConfigurationReadPlatformService {
GlobalConfigurationData retrieveGlobalConfiguration();
GlobalConfigurationPropertyData retrieveGlobalConfiguration(Long configId);
GlobalConfigurationData retrieveGlobalConfiguration(boolean survey);
}
@@ -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,11 +35,20 @@ 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<GlobalConfigurationPropertyData> globalConfiguration = this.jdbcTemplate.query(sql, this.rm, new Object[] {});
return new GlobalConfigurationData(globalConfiguration);
@@ -55,6 +65,8 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl
return globalConfiguration;
}
private static final class GlobalConfigurationRowMapper implements RowMapper<GlobalConfigurationPropertyData> {
@@ -11,4 +11,5 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface GlobalConfigurationWritePlatformService {
CommandProcessingResult update(Long configId, JsonCommand command);
void addSurveyConfig(String name);
}
@@ -66,6 +66,24 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements
}
@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.
@@ -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<String> REGISTER_PARAMS = new HashSet<String>(Arrays.asList(categoryParamName,localParamName));
public static final String DATATABLE_RESOURCE_NAME ="dataTables";
}
@@ -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<GenericResultsetData> 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,
@@ -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<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, REGISTER_PARAMS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
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); }
}
}
@@ -19,6 +19,7 @@ public class DatatableData {
@SuppressWarnings("unused")
private final List<ResultsetColumnHeaderData> columnHeaderData;
public static DatatableData create(final String applicationTableName, final String registeredTableName,
final List<ResultsetColumnHeaderData> columnHeaderData) {
return new DatatableData(applicationTableName, registeredTableName, columnHeaderData);
@@ -29,5 +30,6 @@ public class DatatableData {
this.applicationTableName = applicationTableName;
this.registeredTableName = registeredTableName;
this.columnHeaderData = columnHeaderData;
}
}
@@ -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) {
@@ -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();
}
}
@@ -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<ResultsetColumnHeaderData> columnHeaders = new ArrayList<ResultsetColumnHeaderData>();
final List<ResultsetRowData> resultsetDataRows = new ArrayList<ResultsetRowData>();
@@ -171,6 +176,8 @@ public class GenericDataServiceImpl implements GenericDataService {
@Override
public List<ResultsetColumnHeaderData> fillResultsetColumnHeaders(final String datatable) {
logger.debug("::3 Was inside the fill ResultSetColumnHeader");
final SqlRowSet columnDefinitions = getDatatableMetaData(datatable);
final List<ResultsetColumnHeaderData> columnHeaders = new ArrayList<ResultsetColumnHeaderData>();
@@ -189,13 +196,16 @@ public class GenericDataServiceImpl implements GenericDataService {
List<ResultsetColumnValueData> columnValues = new ArrayList<ResultsetColumnValueData>();
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<ResultsetColumnValueData> retreiveColumnValues(final String codeName) {
final List<ResultsetColumnValueData> columnValues = new ArrayList<ResultsetColumnValueData>();
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<ResultsetColumnValueData> retreiveColumnValues(final Integer codeId) {
final List<ResultsetColumnValueData> columnValues = new ArrayList<ResultsetColumnValueData>();
if (codeId != null) {
final String sql = "select v.id, v.code_value from m_code_value v where v.code_id =" + codeId
@@ -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);
}
@@ -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<ResultsetColumnHeaderData> columnHeaders = this.genericDataService.fillResultsetColumnHeaders(dataTableName);
final Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
final Map<String, String> 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<ResultsetColumnHeaderData> columnHeaders, final String datatable, final String fkName,
final Long appTableId, final Map<String, String> queryParams) {
final Map<String, String> 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<String, Object> 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<String, String> getAffectedColumns(final List<ResultsetColumnHeaderData> columnHeaders,
public Map<String, String> getAffectedColumns(final List<ResultsetColumnHeaderData> columnHeaders,
final Map<String, String> queryParams, final String keyFieldName) {
final String dateFormat = queryParams.get("dateFormat");
@@ -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<String> UPDATE_LIKELIHOOD_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(ACTIVE));
public static final Set<Long> VALID_LIKELIHOOD_ENABLED_VALUES = new HashSet<Long>(
Arrays.asList(
LikelihoodStatus.DISABLED,
LikelihoodStatus.ENABLED
));
}
@@ -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<LikelihoodData> toApiJsonSerializer;
private final PlatformSecurityContext context;
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
private final ReadLikelihoodService readService;
@Autowired
LikelihoodApiResource(final PlatformSecurityContext context,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService,
final DefaultToApiJsonSerializer<LikelihoodData> 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> 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("{ppiName}/{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);
}
}
@@ -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";
}
@@ -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<PpiPovertyLineData> toApiJsonSerializer;
private final DefaultToApiJsonSerializer<LikeliHoodPovertyLineData> likelihoodToApiJsonSerializer;
// private final DefaultToApiJsonSerializer<PpiPovertyLineData> toApiJsonSerializer;
private final PlatformSecurityContext context;
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
private final PovertyLineService readService;
@Autowired
PovertyLineApiResource(final PlatformSecurityContext context,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService,
final DefaultToApiJsonSerializer<PpiPovertyLineData> toApiJsonSerializer,
final PovertyLineService readService,
final DefaultToApiJsonSerializer<LikeliHoodPovertyLineData> 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);
}
}
@@ -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";
}
@@ -0,0 +1,180 @@
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<SurveyData> toApiJsonSerializer;
private final DefaultToApiJsonSerializer<ClientScoresOverview> 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<SurveyData> toApiJsonSerializer,
final PlatformSecurityContext context,
final ReadSurveyService readSurveyService,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService,
final DefaultToApiJsonSerializer<ClientScoresOverview> 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<SurveyDataTableData> 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<ClientScoresOverview> scores = this.readSurveyService.retrieveClientSurveyScoreOverview(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);
}
}
@@ -0,0 +1,35 @@
package org.mifosplatform.infrastructure.survey.data;
import org.joda.time.LocalDate;
/**
* Created by Cieyou on 3/18/14.
*/
public class ClientScoresOverview {
final private String surveyName;
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,
final String surveyName) {
this.likelihoodCode = likelihoodCode;
this.likelihoodName = likelihoodName;
this.score = score;
this.povertyLine = povertyLine;
this.date = date;
this.id = resourceId;
this.surveyName = surveyName;
}
}
@@ -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> povertyLineData;
public LikeliHoodPovertyLineData(final long resourceId, final List<PovertyLineData> 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;
}
}
@@ -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;
}
}
@@ -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<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, LikelihoodApiConstants.UPDATE_LIKELIHOOD_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
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); }
}
}
@@ -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;
}
@@ -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;
}
}
@@ -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> likeliHoodPovertyLineData;
public PpiPovertyLineData(final List<LikeliHoodPovertyLineData> likeliHoodPovertyLineData,
final String ppi){
this.likeliHoodPovertyLineData = likeliHoodPovertyLineData;
this.ppi = ppi;
}
}
@@ -0,0 +1,7 @@
package org.mifosplatform.infrastructure.survey.data;
/**
* Created by Cieyou on 2/27/14.
*/
public class SurveyData {
}
@@ -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;
}
}
@@ -0,0 +1,73 @@
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<Long> {
@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<String, Object> update(final JsonCommand command)
{
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(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();
}
public void disable()
{
this.enabled = LikelihoodStatus.DISABLED;
}
}
@@ -0,0 +1,17 @@
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;
public interface LikelihoodRepository extends JpaRepository<Likelihood, Long>, JpaSpecificationExecutor<Likelihood> {
@Query("FROM Likelihood WHERE ppi_name =:ppiName AND id !=:id")
List<Likelihood> findByPpiNameAndLikeliHoodId(@Param("ppiName") String ppiName,@Param("id") Long likeliHoodId);
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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();
}
@@ -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<LikeliHoodPovertyLineData> listOfLikeliHoodPovertyLineData = new ArrayList<LikeliHoodPovertyLineData>();
while(likelihoods.next())
{
final String codeName = likelihoods.getString("code");
List<PovertyLineData> povertyLineDatas = new ArrayList<PovertyLineData>();
// 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<PovertyLineData> povertyLineDatas = new ArrayList<PovertyLineData>();
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()
// {
//
// }
}
@@ -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<LikelihoodData> retrieveAll(final String ppiName);
public LikelihoodData retrieve(final Long likelihoodId);
}
@@ -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<LikelihoodData> retrieveAll(final String ppiName)
{
final SqlRowSet likelihood =this._getLikelihood(ppiName);
List<LikelihoodData> likelihoodDatas = new ArrayList<LikelihoodData>();
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});
}
}
@@ -0,0 +1,26 @@
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<SurveyDataTableData> retrieveAllSurveys();
SurveyDataTableData retrieveSurvey(String surveyName);
List<ClientScoresOverview>retrieveClientSurveyScoreOverview(String surveyName, Long clientId);
List<ClientScoresOverview>retrieveClientSurveyScoreOverview(Long clientId);
GenericResultsetData retrieveSurveyEntry(String surveyName, Long clientId, Long entryId);
}
@@ -0,0 +1,220 @@
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<SurveyDataTableData> retrieveAllSurveys()
{
String sql = this.retrieveAllSurveySQL("");
final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
final List<SurveyDataTableData> surveyDataTables = new ArrayList<SurveyDataTableData>();
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<ResultsetColumnHeaderData> 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<ResultsetColumnHeaderData> columnHeaderData = this.genericDataService
.fillResultsetColumnHeaders(registeredDatatableName);
datatableData = SurveyDataTableData.create(
DatatableData.create(appTableName, registeredDatatableName, columnHeaderData),
enabled
);
}
return datatableData;
}
public List<ClientScoresOverview> 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<ClientScoresOverview> scoresOverviews = new ArrayList<ClientScoresOverview>();
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"),
surveyName
));
}
return scoresOverviews ;
}
public List<ClientScoresOverview> retrieveClientSurveyScoreOverview(Long clientId)
{
final String surveyNameSql = retrieveAllSurveyNameSQL();
final SqlRowSet surveyNames = this.jdbcTemplate.queryForRowSet(surveyNameSql);
ArrayList<String> sqls = new ArrayList<String>();
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<ClientScoresOverview> scoresOverviews = new ArrayList<ClientScoresOverview>();
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)
{
return readWriteNonCoreDataService.retrieveDataTableGenericResultSet(surveyName, clientId,
null, entryId);
}
}
@@ -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);
}
@@ -0,0 +1,101 @@
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;
import java.util.List;
/**
* 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);
if (!likelihood.update(command).isEmpty()) {
this.repository.save(likelihood);
if(likelihood.isActivateCommand(command))
{
List<Likelihood> likelihoods = this.repository.findByPpiNameAndLikeliHoodId(likelihood.getPpiName(),likelihood.getId());
for(Likelihood aLikelihood:likelihoods)
{
aLikelihood.disable();
}
this.repository.save(likelihoods);
}
}
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());
}
}
@@ -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);
}
@@ -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);
}
}