finish off integration of organisation admin functions in UI with backend services through cross origin request from jQuery.

This commit is contained in:
Keith Woodlock
2012-05-11 14:24:16 +01:00
parent 525831db04
commit f82c87de78
34 changed files with 544 additions and 1946 deletions
@@ -32,5 +32,4 @@ public class ConfigurationData implements Serializable {
public void setCurrencyOptions(List<CurrencyData> currencyOptions) { public void setCurrencyOptions(List<CurrencyData> currencyOptions) {
this.currencyOptions = currencyOptions; this.currencyOptions = currencyOptions;
} }
} }
@@ -5,177 +5,32 @@ import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement @XmlRootElement
public class LoanProductCommand implements LoanProductCommandData { public class LoanProductCommand {
private Long id; private Long id;
private String name; private String name;
private String description; private String description;
private String externalId; private String externalId;
private CommonLoanProperties commonLoanProperties; private String currencyCode;
private Integer digitsAfterDecimal;
private BigDecimal principal;
private BigDecimal inArrearsToleranceAmount;
public LoanProductCommand() { private Integer repaymentEvery;
this.commonLoanProperties = new CommonLoanProperties(); private Integer repaymentFrequency;
} private Integer numberOfRepayments;
public LoanProductCommand(final String currencyCode, private BigDecimal interestRatePerPeriod;
final Integer digitsAfterDecimal, final Number principal, private Integer interestRateFrequencyMethod;
final String name, final String description, private Integer amortizationMethod;
final Number interestRatePerPeriod, Integer interestRateFrequencyMethod, final Integer interestMethod, final Integer interestCalculationPeriodMethod, private Integer interestMethod;
final Integer repaymentEvery, final Integer repaymentFrequency, final Integer numberOfRepayments, Integer amortizationMethod, final Number toleranceAmount, private Integer interestCalculationPeriodMethod;
final boolean flexibleRepaymentSchedule, private boolean flexibleRepaymentSchedule = false;
final boolean interestRebateAllowed) { private boolean interestRebateAllowed = false;
this.name = name;
this.description = description;
commonLoanProperties = new CommonLoanProperties(currencyCode, digitsAfterDecimal, principal, interestRatePerPeriod, interestRateFrequencyMethod, protected LoanProductCommand() {
interestMethod, interestCalculationPeriodMethod, //
repaymentEvery, repaymentFrequency, numberOfRepayments, amortizationMethod, toleranceAmount, flexibleRepaymentSchedule, interestRebateAllowed);
}
@Override
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
@Override
public String getCurrencyCode() {
return this.commonLoanProperties.getCurrencyCode();
}
public void setCurrencyCode(final String currencyCode) {
this.commonLoanProperties.setCurrencyCode(currencyCode);
}
@Override
public Integer getDigitsAfterDecimal() {
return this.commonLoanProperties.getDigitsAfterDecimal();
}
public void setDigitsAfterDecimal(final Integer digitsAfterDecimal) {
this.commonLoanProperties.setDigitsAfterDecimal(digitsAfterDecimal);
}
@Override
public Integer getRepaymentEvery() {
return this.commonLoanProperties.getRepaymentEvery();
}
public void setRepaymentEvery(final Integer repaymentEvery) {
this.commonLoanProperties.setRepaymentEvery(repaymentEvery);
}
@Override
public Integer getRepaymentFrequency() {
return this.commonLoanProperties.getRepaymentFrequency();
}
public void setRepaymentFrequency(final Integer repaymentFrequency) {
this.commonLoanProperties.setRepaymentFrequency(repaymentFrequency);
}
@Override
public Boolean isFlexibleRepaymentSchedule() {
return this.commonLoanProperties.isFlexibleRepaymentSchedule();
}
public void setFlexibleRepaymentSchedule(
final Boolean flexibleRepaymentSchedule) {
this.commonLoanProperties.setFlexibleRepaymentSchedule(flexibleRepaymentSchedule);
}
@Override
public Boolean isInterestRebateAllowed() {
return this.commonLoanProperties.isInterestRebateAllowed();
}
public void setInterestRebateAllowed(final Boolean interestRebateAllowed) {
this.commonLoanProperties.setInterestRebateAllowed(interestRebateAllowed);
}
@Override
public BigDecimal getPrincipal() {
return this.commonLoanProperties.getPrincipal();
}
public void setPrincipal(final BigDecimal principal) {
this.commonLoanProperties.setPrincipal(principal);
}
@Override
public Integer getInterestRateFrequencyMethod() {
return commonLoanProperties.getInterestRateFrequencyMethod();
}
public void setInterestRateFrequencyMethod(Integer interestRateFrequencyMethod) {
this.commonLoanProperties.setInterestRateFrequencyMethod(interestRateFrequencyMethod);
}
@Override
public Integer getInterestMethod() {
return commonLoanProperties.getInterestMethod();
}
public void setInterestMethod(Integer interestMethod) {
this.commonLoanProperties.setInterestMethod(interestMethod);
}
@Override
public Integer getAmortizationMethod() {
return commonLoanProperties.getAmortizationMethod();
}
public void setAmortizationMethod(Integer amortizationMethod) {
this.commonLoanProperties.setAmortizationMethod(amortizationMethod);
}
@Override
public Integer getNumberOfRepayments() {
return commonLoanProperties.getNumberOfRepayments();
}
public void setNumberOfRepayments(Integer numberOfRepayments) {
this.commonLoanProperties.setNumberOfRepayments(numberOfRepayments);
}
@Override
public BigDecimal getInterestRatePerPeriod() {
return commonLoanProperties.getInterestRatePerPeriod();
}
public void setInterestRatePerPeriod(BigDecimal interestRatePerPeriod) {
this.commonLoanProperties.setInterestRatePerPeriod(interestRatePerPeriod);
}
@Override
public CommonLoanProperties getCommonLoanProperties() {
return commonLoanProperties;
}
public void setCommonLoanProperties(CommonLoanProperties commonLoanProperties) {
this.commonLoanProperties = commonLoanProperties;
}
@Override
public BigDecimal getInArrearsToleranceAmount() {
return this.commonLoanProperties.getInArrearsToleranceAmount();
}
public void setInArrearsToleranceAmount(BigDecimal inArrearsToleranceAmount) {
this.commonLoanProperties.setInArrearsToleranceAmount(inArrearsToleranceAmount);
} }
public Long getId() { public Long getId() {
@@ -186,6 +41,22 @@ public class LoanProductCommand implements LoanProductCommandData {
this.id = id; this.id = id;
} }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExternalId() { public String getExternalId() {
return externalId; return externalId;
} }
@@ -194,12 +65,116 @@ public class LoanProductCommand implements LoanProductCommandData {
this.externalId = externalId; this.externalId = externalId;
} }
@Override public String getCurrencyCode() {
public Integer getInterestCalculationPeriodMethod() { return currencyCode;
return this.commonLoanProperties.getInterestCalculationPeriodMethod();
} }
public void setInterestCalculationPeriodMethod(final Integer interestCalculationPeriodMethod) { public void setCurrencyCode(String currencyCode) {
this.commonLoanProperties.setInterestCalculationPeriodMethod(interestCalculationPeriodMethod); this.currencyCode = currencyCode;
}
public Integer getDigitsAfterDecimal() {
return digitsAfterDecimal;
}
public void setDigitsAfterDecimal(Integer digitsAfterDecimal) {
this.digitsAfterDecimal = digitsAfterDecimal;
}
public BigDecimal getPrincipal() {
return principal;
}
public void setPrincipal(BigDecimal principal) {
this.principal = principal;
}
public BigDecimal getInArrearsToleranceAmount() {
return inArrearsToleranceAmount;
}
public void setInArrearsToleranceAmount(BigDecimal inArrearsToleranceAmount) {
this.inArrearsToleranceAmount = inArrearsToleranceAmount;
}
public Integer getRepaymentEvery() {
return repaymentEvery;
}
public void setRepaymentEvery(Integer repaymentEvery) {
this.repaymentEvery = repaymentEvery;
}
public Integer getRepaymentFrequency() {
return repaymentFrequency;
}
public void setRepaymentFrequency(Integer repaymentFrequency) {
this.repaymentFrequency = repaymentFrequency;
}
public Integer getNumberOfRepayments() {
return numberOfRepayments;
}
public void setNumberOfRepayments(Integer numberOfRepayments) {
this.numberOfRepayments = numberOfRepayments;
}
public BigDecimal getInterestRatePerPeriod() {
return interestRatePerPeriod;
}
public void setInterestRatePerPeriod(BigDecimal interestRatePerPeriod) {
this.interestRatePerPeriod = interestRatePerPeriod;
}
public Integer getInterestRateFrequencyMethod() {
return interestRateFrequencyMethod;
}
public void setInterestRateFrequencyMethod(Integer interestRateFrequencyMethod) {
this.interestRateFrequencyMethod = interestRateFrequencyMethod;
}
public Integer getAmortizationMethod() {
return amortizationMethod;
}
public void setAmortizationMethod(Integer amortizationMethod) {
this.amortizationMethod = amortizationMethod;
}
public Integer getInterestMethod() {
return interestMethod;
}
public void setInterestMethod(Integer interestMethod) {
this.interestMethod = interestMethod;
}
public Integer getInterestCalculationPeriodMethod() {
return interestCalculationPeriodMethod;
}
public void setInterestCalculationPeriodMethod(
Integer interestCalculationPeriodMethod) {
this.interestCalculationPeriodMethod = interestCalculationPeriodMethod;
}
public boolean isFlexibleRepaymentSchedule() {
return flexibleRepaymentSchedule;
}
public void setFlexibleRepaymentSchedule(boolean flexibleRepaymentSchedule) {
this.flexibleRepaymentSchedule = flexibleRepaymentSchedule;
}
public boolean isInterestRebateAllowed() {
return interestRebateAllowed;
}
public void setInterestRebateAllowed(boolean interestRebateAllowed) {
this.interestRebateAllowed = interestRebateAllowed;
} }
} }
@@ -14,9 +14,12 @@ public class OfficeCommand {
private String name; private String name;
private String externalId; private String externalId;
private String dateFormat;
private String openingDateFormatted;
private LocalDate openingDate; private LocalDate openingDate;
private Long parentId; private Long parentId;
private boolean rootOffice = false;
protected OfficeCommand() { protected OfficeCommand() {
// //
@@ -79,4 +82,28 @@ public class OfficeCommand {
public void setId(final Long id) { public void setId(final Long id) {
this.id = id; this.id = id;
} }
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public String getOpeningDateFormatted() {
return openingDateFormatted;
}
public void setOpeningDateFormatted(String openingDateFormatted) {
this.openingDateFormatted = openingDateFormatted;
}
public boolean isRootOffice() {
return rootOffice;
}
public void setRootOffice(boolean rootOffice) {
this.rootOffice = rootOffice;
}
} }
@@ -0,0 +1,39 @@
package org.mifosng.data.command;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class OrganisationCurrencyCommand implements Serializable {
private Collection<String> notSelectedItems = new ArrayList<String>();
private Collection<String> selectedItems = new ArrayList<String>();
public OrganisationCurrencyCommand() {
//
}
public OrganisationCurrencyCommand(final List<String> selectedCurrencyCodes) {
this.selectedItems = selectedCurrencyCodes;
}
public Collection<String> getSelectedItems() {
return selectedItems;
}
public void setSelectedItems(Collection<String> selectedItems) {
this.selectedItems = selectedItems;
}
public Collection<String> getNotSelectedItems() {
return notSelectedItems;
}
public void setNotSelectedItems(Collection<String> notSelectedItems) {
this.notSelectedItems = notSelectedItems;
}
}
@@ -1,30 +0,0 @@
package org.mifosng.data.command;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class UpdateOrganisationCurrencyCommand implements Serializable {
private Collection<String> codes = new ArrayList<String>();
public UpdateOrganisationCurrencyCommand() {
//
}
public UpdateOrganisationCurrencyCommand(final List<String> currencyCodes) {
this.codes = currencyCodes;
}
public Collection<String> getCodes() {
return this.codes;
}
public void setCodes(final Collection<String> codes) {
this.codes = codes;
}
}
@@ -6,7 +6,6 @@ import java.util.Map;
import org.mifosng.data.AppUserData; import org.mifosng.data.AppUserData;
import org.mifosng.data.ClientData; import org.mifosng.data.ClientData;
import org.mifosng.data.ClientDataWithAccountsData; import org.mifosng.data.ClientDataWithAccountsData;
import org.mifosng.data.CurrencyData;
import org.mifosng.data.EntityIdentifier; import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.EnumOptionReadModel; import org.mifosng.data.EnumOptionReadModel;
import org.mifosng.data.LoanAccountData; import org.mifosng.data.LoanAccountData;
@@ -15,23 +14,19 @@ import org.mifosng.data.LoanRepaymentData;
import org.mifosng.data.LoanSchedule; import org.mifosng.data.LoanSchedule;
import org.mifosng.data.NewLoanWorkflowStepOneData; import org.mifosng.data.NewLoanWorkflowStepOneData;
import org.mifosng.data.NoteData; import org.mifosng.data.NoteData;
import org.mifosng.data.OfficeData;
import org.mifosng.data.PermissionData; import org.mifosng.data.PermissionData;
import org.mifosng.data.RoleData; import org.mifosng.data.RoleData;
import org.mifosng.data.command.AdjustLoanTransactionCommand; import org.mifosng.data.command.AdjustLoanTransactionCommand;
import org.mifosng.data.command.CalculateLoanScheduleCommand; import org.mifosng.data.command.CalculateLoanScheduleCommand;
import org.mifosng.data.command.ChangePasswordCommand; import org.mifosng.data.command.ChangePasswordCommand;
import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.EnrollClientCommand;
import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanStateTransitionCommand;
import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.LoanTransactionCommand;
import org.mifosng.data.command.NoteCommand; import org.mifosng.data.command.NoteCommand;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.RoleCommand;
import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand;
import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanApprovalCommand;
import org.mifosng.data.command.UndoLoanDisbursalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand;
import org.mifosng.data.command.UpdateOrganisationCurrencyCommand;
import org.mifosng.data.command.UserCommand; import org.mifosng.data.command.UserCommand;
import org.mifosng.data.reports.GenericResultset; import org.mifosng.data.reports.GenericResultset;
import org.springframework.security.oauth.consumer.ProtectedResourceDetails; import org.springframework.security.oauth.consumer.ProtectedResourceDetails;
@@ -43,12 +38,6 @@ public interface CommonRestOperations {
void updateProtectedResource( void updateProtectedResource(
ProtectedResourceDetails loadProtectedResourceDetailsById); ProtectedResourceDetails loadProtectedResourceDetailsById);
void updateOrganisationCurrencies(UpdateOrganisationCurrencyCommand command);
Collection<OfficeData> retrieveAllOffices();
OfficeData retrieveOffice(Long officeId);
Collection<AppUserData> retrieveAllUsers(); Collection<AppUserData> retrieveAllUsers();
AppUserData retrieveNewUserDetails(); AppUserData retrieveNewUserDetails();
@@ -79,34 +68,10 @@ public interface CommonRestOperations {
EntityIdentifier createRole(RoleCommand command); EntityIdentifier createRole(RoleCommand command);
EntityIdentifier createOffice(OfficeCommand command);
EntityIdentifier updateOffice(OfficeCommand command);
Collection<ClientData> retrieveAllIndividualClients(); Collection<ClientData> retrieveAllIndividualClients();
Collection<LoanProductData> retrieveAllLoanProducts(); Collection<LoanProductData> retrieveAllLoanProducts();
Collection<CurrencyData> retrieveAllowedCurrencies();
Collection<CurrencyData> retrieveAllPlatformCurrencies();
Collection<EnumOptionReadModel> retrieveAllowedLoanAmortizationMethodOptions();
Collection<EnumOptionReadModel> retrieveAllowedLoanInterestMethodOptions();
Collection<EnumOptionReadModel> retrieveAllowedRepaymentFrequencyOptions();
Collection<EnumOptionReadModel> retrieveAllowedNominalInterestFrequencyOptions();
EntityIdentifier createLoanProduct(LoanProductCommand command);
EntityIdentifier updateLoanProduct(LoanProductCommand command);
LoanProductData retrieveLoanProductDetails(Long selectedLoanProductOption);
LoanProductData retrieveNewLoanProductDetails();
LoanSchedule calculateLoanSchedule(CalculateLoanScheduleCommand command); LoanSchedule calculateLoanSchedule(CalculateLoanScheduleCommand command);
NewLoanWorkflowStepOneData retrieveNewLoanApplicationStepOneDetails( NewLoanWorkflowStepOneData retrieveNewLoanApplicationStepOneDetails(
@@ -13,8 +13,6 @@ import org.mifosng.data.AppUserData;
import org.mifosng.data.ClientData; import org.mifosng.data.ClientData;
import org.mifosng.data.ClientDataWithAccountsData; import org.mifosng.data.ClientDataWithAccountsData;
import org.mifosng.data.ClientList; import org.mifosng.data.ClientList;
import org.mifosng.data.CurrencyData;
import org.mifosng.data.CurrencyList;
import org.mifosng.data.EntityIdentifier; import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.EnumOptionList; import org.mifosng.data.EnumOptionList;
import org.mifosng.data.EnumOptionReadModel; import org.mifosng.data.EnumOptionReadModel;
@@ -28,8 +26,6 @@ import org.mifosng.data.LoanSchedule;
import org.mifosng.data.NewLoanWorkflowStepOneData; import org.mifosng.data.NewLoanWorkflowStepOneData;
import org.mifosng.data.NoteData; import org.mifosng.data.NoteData;
import org.mifosng.data.NoteDataList; import org.mifosng.data.NoteDataList;
import org.mifosng.data.OfficeData;
import org.mifosng.data.OfficeList;
import org.mifosng.data.PermissionData; import org.mifosng.data.PermissionData;
import org.mifosng.data.PermissionList; import org.mifosng.data.PermissionList;
import org.mifosng.data.RoleData; import org.mifosng.data.RoleData;
@@ -39,16 +35,13 @@ import org.mifosng.data.command.AdjustLoanTransactionCommand;
import org.mifosng.data.command.CalculateLoanScheduleCommand; import org.mifosng.data.command.CalculateLoanScheduleCommand;
import org.mifosng.data.command.ChangePasswordCommand; import org.mifosng.data.command.ChangePasswordCommand;
import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.EnrollClientCommand;
import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanStateTransitionCommand;
import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.LoanTransactionCommand;
import org.mifosng.data.command.NoteCommand; import org.mifosng.data.command.NoteCommand;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.RoleCommand;
import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand;
import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanApprovalCommand;
import org.mifosng.data.command.UndoLoanDisbursalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand;
import org.mifosng.data.command.UpdateOrganisationCurrencyCommand;
import org.mifosng.data.command.UserCommand; import org.mifosng.data.command.UserCommand;
import org.mifosng.data.reports.GenericResultset; import org.mifosng.data.reports.GenericResultset;
import org.mifosng.ui.loanproduct.ClientValidationException; import org.mifosng.ui.loanproduct.ClientValidationException;
@@ -129,38 +122,7 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
return s.getBody().getProducts(); return s.getBody().getProducts();
} }
@Override
public EntityIdentifier createLoanProduct(final LoanProductCommand command) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/product/loan/new"));
ResponseEntity<EntityIdentifier> s = this.oauthRestServiceTemplate.postForEntity(restUri,
updateLoanProductRequest(command), EntityIdentifier.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public EntityIdentifier updateLoanProduct(LoanProductCommand command) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/product/loan/update"));
ResponseEntity<EntityIdentifier> s = this.oauthRestServiceTemplate
.postForEntity(restUri, updateLoanProductRequest(command),
EntityIdentifier.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
private ErrorResponseList parseErrors(HttpStatusCodeException e) { private ErrorResponseList parseErrors(HttpStatusCodeException e) {
@@ -185,53 +147,6 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
return errorList; return errorList;
} }
private HttpEntity<LoanProductCommand> updateLoanProductRequest(
final LoanProductCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
HttpEntity<LoanProductCommand> requestEntity = new HttpEntity<LoanProductCommand>(
command, requestHeaders);
return requestEntity;
}
@Override
public LoanProductData retrieveLoanProductDetails(
final Long selectedLoanProductOption) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/product/loan/"
+ selectedLoanProductOption));
ResponseEntity<LoanProductData> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
LoanProductData.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public LoanProductData retrieveNewLoanProductDetails() {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/product/loan/empty"));
ResponseEntity<LoanProductData> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
LoanProductData.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override @Override
public LoanSchedule calculateLoanSchedule( public LoanSchedule calculateLoanSchedule(
final CalculateLoanScheduleCommand command) { final CalculateLoanScheduleCommand command) {
@@ -588,115 +503,6 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
requestHeaders); requestHeaders);
} }
@Override
public Collection<CurrencyData> retrieveAllowedCurrencies() {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/currency/allowed"));
ResponseEntity<CurrencyList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
CurrencyList.class);
return s.getBody().getCurrencies();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public Collection<EnumOptionReadModel> retrieveAllowedLoanAmortizationMethodOptions() {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/loan/amortization/allowed"));
ResponseEntity<EnumOptionList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
EnumOptionList.class);
return s.getBody().getOptions();
}
@Override
public Collection<EnumOptionReadModel> retrieveAllowedLoanInterestMethodOptions() {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/loan/interestcalculation/allowed"));
ResponseEntity<EnumOptionList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
EnumOptionList.class);
return s.getBody().getOptions();
}
@Override
public Collection<EnumOptionReadModel> retrieveAllowedRepaymentFrequencyOptions() {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/loan/repaymentfrequency/allowed"));
ResponseEntity<EnumOptionList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
EnumOptionList.class);
return s.getBody().getOptions();
}
@Override
public Collection<EnumOptionReadModel> retrieveAllowedNominalInterestFrequencyOptions() {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/loan/interestfrequency/allowed"));
ResponseEntity<EnumOptionList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
EnumOptionList.class);
return s.getBody().getOptions();
}
@Override
public Collection<CurrencyData> retrieveAllPlatformCurrencies() {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/currency/all"));
ResponseEntity<CurrencyList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
CurrencyList.class);
return s.getBody().getCurrencies();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public void updateOrganisationCurrencies(UpdateOrganisationCurrencyCommand command) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/config/currency/update"));
this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.PUT,
updateCurrencyRequest(command),
UpdateOrganisationCurrencyCommand.class);
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
private HttpEntity<UpdateOrganisationCurrencyCommand> updateCurrencyRequest(
final UpdateOrganisationCurrencyCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
HttpEntity<UpdateOrganisationCurrencyCommand> requestEntity = new HttpEntity<UpdateOrganisationCurrencyCommand>(
command, requestHeaders);
return requestEntity;
}
@Override @Override
public EntityIdentifier createUser(final UserCommand command) { public EntityIdentifier createUser(final UserCommand command) {
try { try {
@@ -950,99 +756,6 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
} }
} }
@Override
public Collection<OfficeData> retrieveAllOffices() {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/office/all"));
ResponseEntity<OfficeList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
OfficeList.class);
return s.getBody().getOffices();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public OfficeData retrieveOffice(final Long officeId) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/office/"
+ officeId));
ResponseEntity<OfficeData> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
OfficeData.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public EntityIdentifier createOffice(final OfficeCommand command) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/office/new"));
ResponseEntity<EntityIdentifier> s = this.oauthRestServiceTemplate
.postForEntity(restUri, createOfficeRequest(command),
EntityIdentifier.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
@Override
public EntityIdentifier updateOffice(final OfficeCommand command) {
try {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/office/update"));
ResponseEntity<EntityIdentifier> s = this.oauthRestServiceTemplate
.postForEntity(restUri, updateOfficeRequest(command),
EntityIdentifier.class);
return s.getBody();
} catch (HttpStatusCodeException e) {
ErrorResponseList errorList = parseErrors(e);
throw new ClientValidationException(errorList.getErrors());
}
}
private HttpEntity<OfficeCommand> createOfficeRequest(
final OfficeCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
HttpEntity<OfficeCommand> requestEntity = new HttpEntity<OfficeCommand>(
command, requestHeaders);
return requestEntity;
}
private HttpEntity<OfficeCommand> updateOfficeRequest(
final OfficeCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
HttpEntity<OfficeCommand> requestEntity = new HttpEntity<OfficeCommand>(
command, requestHeaders);
return requestEntity;
}
@Override @Override
public ClientData retrieveNewIndividualClient() { public ClientData retrieveNewIndividualClient() {
URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/new")); URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/new"));
@@ -1,35 +1,24 @@
package org.mifosng.ui.configuration; package org.mifosng.ui.configuration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.mifosng.configuration.ApplicationConfigurationService; import org.mifosng.configuration.ApplicationConfigurationService;
import org.mifosng.configuration.OAuthProviderDetails; import org.mifosng.configuration.OAuthProviderDetails;
import org.mifosng.data.ConfigurationData;
import org.mifosng.data.CurrencyData;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse; import org.mifosng.data.ErrorResponse;
import org.mifosng.data.command.UpdateOrganisationCurrencyCommand;
import org.mifosng.oauth.RefreshableProtectedResourceDetailsService; import org.mifosng.oauth.RefreshableProtectedResourceDetailsService;
import org.mifosng.ui.CommonRestOperations; import org.mifosng.ui.CommonRestOperations;
import org.mifosng.ui.loanproduct.ClientValidationException; import org.mifosng.ui.loanproduct.ClientValidationException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth.consumer.ProtectedResourceDetailsService; import org.springframework.security.oauth.consumer.ProtectedResourceDetailsService;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@@ -66,38 +55,6 @@ public class ConfigurationController {
return ex.getValidationErrors(); return ex.getValidationErrors();
} }
@RequestMapping(consumes="application/json", produces="application/json", value = "org/configuration/edit", method = RequestMethod.GET)
public @ResponseBody ConfigurationData viewConfigurationDetails() {
List<CurrencyData> selectedCurrencyOptions = new ArrayList<CurrencyData>(this.commonRestOperations.retrieveAllowedCurrencies());
List<CurrencyData> currencyOptions = new ArrayList<CurrencyData>(this.commonRestOperations.retrieveAllPlatformCurrencies());
// remove selected currency options
currencyOptions.removeAll(selectedCurrencyOptions);
ConfigurationData configurationData = new ConfigurationData();
configurationData.setCurrencyOptions(currencyOptions);
configurationData.setSelectedCurrencyOptions(selectedCurrencyOptions);
return configurationData;
}
@RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "org/configuration/edit", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody EntityIdentifier updateOrganisationCurrencies(@RequestParam(value="selectedItems", required=false) String[] selectedCurrencies) {
List<String> codes = new ArrayList<String>();
if (selectedCurrencies != null) {
codes = Arrays.asList(selectedCurrencies);
}
UpdateOrganisationCurrencyCommand command = new UpdateOrganisationCurrencyCommand(codes);
this.commonRestOperations.updateOrganisationCurrencies(command);
return new EntityIdentifier(Long.valueOf(1));
}
@ModelAttribute("oauthSettingsFormBean") @ModelAttribute("oauthSettingsFormBean")
@RequestMapping(value = "oauth/configuration/edit", method = RequestMethod.GET) @RequestMapping(value = "oauth/configuration/edit", method = RequestMethod.GET)
public ModelAndView showOAuthConfiguration() { public ModelAndView showOAuthConfiguration() {
@@ -114,9 +71,7 @@ public class ConfigurationController {
} }
@RequestMapping(value = "oauth/configuration/edit", method = RequestMethod.POST) @RequestMapping(value = "oauth/configuration/edit", method = RequestMethod.POST)
public ModelAndView updateOAuthConfiguration( public ModelAndView updateOAuthConfiguration(@ModelAttribute final OauthSettingsFormBean oauthSettingsFormBean) {
@ModelAttribute final OauthSettingsFormBean oauthSettingsFormBean,
final BindingResult result) {
ModelAndView mav = new ModelAndView("redirect:/"); ModelAndView mav = new ModelAndView("redirect:/");
@@ -1,195 +0,0 @@
package org.mifosng.ui.loanproduct;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.LoanProductData;
import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.ui.CommonRestOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
public class LoanProductController {
private final CommonRestOperations commonRestOperations;
@Autowired
public LoanProductController(final CommonRestOperations commonRestOperations) {
this.commonRestOperations = commonRestOperations;
}
@ExceptionHandler(AccessDeniedException.class)
public String accessDeniedException() {
return "unAuthorizedAction";
}
@ExceptionHandler(ClientValidationException.class)
public @ResponseBody Collection<ErrorResponse> validationException(ClientValidationException ex, HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("application/json");
return ex.getValidationErrors();
}
private BigDecimal parseStringToBigDecimal(String source) {
try {
BigDecimal number = null;
if (StringUtils.isNotBlank(source)) {
String sourceWithoutSpaces = source.replaceAll(" ", "");
Locale locale = LocaleContextHolder.getLocale();
NumberFormat format = NumberFormat.getNumberInstance(locale);
Number parsedNumber = format.parse(sourceWithoutSpaces);
number = BigDecimal.valueOf(Double.valueOf(parsedNumber
.doubleValue()));
}
return number;
} catch (ParseException e) {
List<ErrorResponse> validationErrors = new ArrayList<ErrorResponse>();
validationErrors.add(new ErrorResponse("validation.msg.invalid.number.format", "amount", source));
throw new ClientValidationException(validationErrors);
}
}
@RequestMapping(consumes="application/json", produces="application/json", value = "/portfolio/product/loan/all", method = RequestMethod.GET)
public @ResponseBody Collection<LoanProductData> viewAllLoanProducts() {
return this.commonRestOperations.retrieveAllLoanProducts();
}
@RequestMapping(consumes="application/json", produces="application/json", value = "/portfolio/product/loan/new", method = RequestMethod.GET)
public @ResponseBody LoanProductData viewNewLoanProductForm() {
return this.commonRestOperations.retrieveNewLoanProductDetails();
}
@RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "/portfolio/product/loan/new", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody EntityIdentifier createLoanProduct(
@RequestParam("name") String name,
@RequestParam("description") String description,
@RequestParam("selectedCurrency") String currencyCode, @RequestParam("selectedDigitsAfterDecimal") Integer digitsAfterDecimal,
@RequestParam("amount") String principalAsNumber,
@RequestParam("repaidEvery") Integer repaymentEvery,
@RequestParam("selectedRepaymentFrequencyOption") Integer repaymentFrequency,
@RequestParam("numberOfRepayments") Integer numberOfRepayments,
@RequestParam("selectedAmortizationMethodOption") Integer amortizationMethod,
@RequestParam("inArrearsTolerance") String inArrearsToleranceAsNumber,
@RequestParam("nominalInterestRate") String nominalInterestRatePerPeriodAsNumber,
@RequestParam("selectedInterestFrequencyOption") Integer nominalInterestRatePerPeriodFrequency,
@RequestParam("selectedInterestMethodOption") Integer interestMethod,
@RequestParam(value="interestRateCalculatedInPeriod", required=false) Integer interestCalculationPeriodMethod
) {
LoanProductCommand command = new LoanProductCommand();
command.setName(name);
command.setDescription(description);
command.setCurrencyCode(currencyCode);
command.setDigitsAfterDecimal(digitsAfterDecimal);
if (StringUtils.isNotBlank(principalAsNumber)) {
BigDecimal principal = parseStringToBigDecimal(principalAsNumber);
command.setPrincipal(principal);
}
command.setRepaymentEvery(repaymentEvery);
command.setRepaymentFrequency(repaymentFrequency);
command.setNumberOfRepayments(numberOfRepayments);
command.setAmortizationMethod(amortizationMethod);
if (StringUtils.isNotBlank(inArrearsToleranceAsNumber)) {
BigDecimal inArrearsToleranceAmount = parseStringToBigDecimal(inArrearsToleranceAsNumber);
command.setInArrearsToleranceAmount(inArrearsToleranceAmount);
}
if (StringUtils.isNotBlank(nominalInterestRatePerPeriodAsNumber)) {
BigDecimal interestRatePerPeriod = parseStringToBigDecimal(nominalInterestRatePerPeriodAsNumber);
command.setInterestRatePerPeriod(interestRatePerPeriod);
}
command.setInterestRateFrequencyMethod(nominalInterestRatePerPeriodFrequency);
command.setInterestMethod(interestMethod);
command.setInterestCalculationPeriodMethod(interestCalculationPeriodMethod);
return this.commonRestOperations.createLoanProduct(command);
}
@RequestMapping(consumes="application/json", produces="application/json", value = "/portfolio/product/loan/{productId}", method = RequestMethod.GET)
public @ResponseBody LoanProductData viewLoanProduct(@PathVariable("productId") final Long productId) {
return this.commonRestOperations.retrieveLoanProductDetails(productId);
}
@RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "/portfolio/product/loan/{productId}", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody EntityIdentifier updateLoanProduct(@PathVariable("productId") final Long productId,
@RequestParam("name") String name, @RequestParam("description") String description,
@RequestParam("selectedCurrency") String currencyCode, @RequestParam("selectedDigitsAfterDecimal") Integer digitsAfterDecimal,
@RequestParam("amount") String principalAsNumber,
@RequestParam("repaidEvery") Integer repaymentEvery,
@RequestParam("selectedRepaymentFrequencyOption") Integer repaymentFrequency,
@RequestParam("numberOfRepayments") Integer numberOfRepayments,
@RequestParam("selectedAmortizationMethodOption") Integer amortizationMethod,
@RequestParam("inArrearsTolerance") String inArrearsToleranceAsNumber,
@RequestParam("nominalInterestRate") String nominalInterestRatePerPeriodAsNumber,
@RequestParam("selectedInterestFrequencyOption") Integer nominalInterestRatePerPeriodFrequency,
@RequestParam("selectedInterestMethodOption") Integer interestMethod,
@RequestParam(value="interestRateCalculatedInPeriod", required=false) Integer interestCalculationPeriodMethod
) {
LoanProductCommand command = new LoanProductCommand();
command.setId(productId);
command.setName(name);
command.setDescription(description);
command.setExternalId(null);
command.setCurrencyCode(currencyCode);
command.setDigitsAfterDecimal(digitsAfterDecimal);
if (StringUtils.isNotBlank(principalAsNumber)) {
BigDecimal principal = parseStringToBigDecimal(principalAsNumber);
command.setPrincipal(principal);
}
command.setRepaymentEvery(repaymentEvery);
command.setRepaymentFrequency(repaymentFrequency);
command.setNumberOfRepayments(numberOfRepayments);
command.setAmortizationMethod(amortizationMethod);
if (StringUtils.isNotBlank(inArrearsToleranceAsNumber)) {
BigDecimal inArrearsToleranceAmount = parseStringToBigDecimal(inArrearsToleranceAsNumber);
command.setInArrearsToleranceAmount(inArrearsToleranceAmount);
}
if (StringUtils.isNotBlank(nominalInterestRatePerPeriodAsNumber)) {
BigDecimal interestRatePerPeriod = parseStringToBigDecimal(nominalInterestRatePerPeriodAsNumber);
command.setInterestRatePerPeriod(interestRatePerPeriod);
}
command.setInterestRateFrequencyMethod(nominalInterestRatePerPeriodFrequency);
command.setInterestMethod(interestMethod);
command.setInterestCalculationPeriodMethod(interestCalculationPeriodMethod);
return this.commonRestOperations.updateLoanProduct(command);
}
}
@@ -1,127 +0,0 @@
package org.mifosng.ui.office;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.OfficeData;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.ui.CommonRestOperations;
import org.mifosng.ui.loanproduct.ClientValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
public class OfficeController {
private final CommonRestOperations commonRestOperations;
@Autowired
public OfficeController(final CommonRestOperations commonRestOperations) {
this.commonRestOperations = commonRestOperations;
}
@ExceptionHandler(AccessDeniedException.class)
public String accessDeniedException() {
return "unAuthorizedAction";
}
@ExceptionHandler(ClientValidationException.class)
public @ResponseBody
Collection<ErrorResponse> validationException(ClientValidationException ex,
HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("application/json");
return ex.getValidationErrors();
}
private LocalDate parseStringToLocalDate(String eventDate, String dateFieldIdentifier) {
LocalDate eventLocalDate = null;
if (StringUtils.isNotBlank(eventDate)) {
try {
Locale locale = LocaleContextHolder.getLocale();
eventLocalDate = DateTimeFormat.forPattern("dd MMMM yyyy").withLocale(locale).parseLocalDate(eventDate.toLowerCase(locale));
} catch (IllegalArgumentException e) {
List<ErrorResponse> validationErrors = new ArrayList<ErrorResponse>();
validationErrors.add(new ErrorResponse("validation.msg.invalid.date.format", dateFieldIdentifier, eventDate));
throw new ClientValidationException(validationErrors);
}
}
return eventLocalDate;
}
@RequestMapping(consumes="application/json", produces="application/json", value = "/org/office/all", method = RequestMethod.GET)
public @ResponseBody Collection<OfficeData> viewAllOffices() {
return this.commonRestOperations.retrieveAllOffices();
}
@RequestMapping(consumes="application/json", produces="application/json", value = "/org/office/new", method = RequestMethod.GET)
public @ResponseBody OfficeData viewNewOfficeForm() {
OfficeData newOffice = new OfficeData();
newOffice.setOpeningDate(new LocalDate());
Collection<OfficeData> allOffices = this.commonRestOperations.retrieveAllOffices();
List<OfficeData> allowedParents = new ArrayList<OfficeData>(allOffices);
newOffice.setAllowedParents(allowedParents);
return newOffice;
}
@RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "/org/office/new", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody EntityIdentifier createOffice(
@RequestParam("name") String name,
@RequestParam(value="parentId", required=false) Long parentId,
@RequestParam("openingDate") String openingDate,
@RequestParam(value="externalId", required=false) String externalId) {
LocalDate openingLocalDate = parseStringToLocalDate(openingDate, "openingDate");
OfficeCommand command = new OfficeCommand(name, externalId, parentId, openingLocalDate);
return this.commonRestOperations.createOffice(command);
}
@RequestMapping(consumes="application/json", produces="application/json", value = "/org/office/{officeId}", method = RequestMethod.GET)
public @ResponseBody OfficeData viewOffice(@PathVariable("officeId") final Long officeId) {
return this.commonRestOperations.retrieveOffice(officeId);
}
@RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "/org/office/{officeId}", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody EntityIdentifier updateOffice(@PathVariable("officeId") final Long officeId,
@RequestParam("name") String name,
@RequestParam(value="parentId", required=false) Long parentId,
@RequestParam("openingDate") String openingDate,
@RequestParam(value="externalId", required=false) String externalId) {
LocalDate openingLocalDate = parseStringToLocalDate(openingDate, "openingDate");
OfficeCommand command = new OfficeCommand(officeId, name, externalId, parentId, openingLocalDate);
return this.commonRestOperations.updateOffice(command);
}
}
@@ -250,7 +250,7 @@ validation.msg.product.interest.rate.per.period.amount.cannot.be.empty=Nominal i
validation.msg.product.currency.digitsAfterDecimal.must.be.between.zero.and.six.inclusive=Decimal places must be a number between zero and six inclusive. validation.msg.product.currency.digitsAfterDecimal.must.be.between.zero.and.six.inclusive=Decimal places must be a number between zero and six inclusive.
validation.msg.product.principal.amount.must.be.greater.than.zero=Loan amount must be greater than zero. validation.msg.product.principal.amount.must.be.greater.than.zero=Loan amount must be greater than zero.
validation.msg.product.repayment.repaidEvery.outside.allowed.range=Repaid every is out of allowed range for selected repayment frequency type. validation.msg.product.repayment.repaidEvery.outside.allowed.range=Repaid every must be between {0} and {1} inclusive given the selected repayment frequency type.
validation.msg.product.number.of.repayments.is.out.of.range=# of repayments is out of allowed range for selected repayment frequency type. validation.msg.product.number.of.repayments.is.out.of.range=# of repayments is out of allowed range for selected repayment frequency type.
validation.msg.product.arrears.tolerance.amount.cannot.be.negative=Arrears tolerance cannot be negative. validation.msg.product.arrears.tolerance.amount.cannot.be.negative=Arrears tolerance cannot be negative.
validation.msg.product.interest.rate.per.period.amount.cannot.be.negative=Nominal interest rate % cannot be negative. validation.msg.product.interest.rate.per.period.amount.cannot.be.negative=Nominal interest rate % cannot be negative.
@@ -112,17 +112,28 @@
removeErrors(placeholderDiv); removeErrors(placeholderDiv);
var jsonErrors = JSON.parse(jqXHR.responseText); var jsonErrors = JSON.parse(jqXHR.responseText);
console.log(jsonErrors);
var valErrors = jsonErrors.errors;
console.log(valErrors);
var errorArray = new Array(); var errorArray = new Array();
var arrayIndex = 0; var arrayIndex = 0;
$.each(jsonErrors, function() { $.each(valErrors, function() {
var fieldId = '#' + this.field; var fieldId = '#' + this.parameterName;
$(fieldId).addClass("ui-state-error"); $(fieldId).addClass("ui-state-error");
var errorObj = new Object(); var errorObj = new Object();
errorObj.field = this.field; errorObj.field = this.parameterName;
errorObj.code = this.code; errorObj.code = this.userMessageGlobalisationCode;
errorObj.message = jQuery.i18n.prop(this.code, this.args);
var argArray = new Array();
var argArrayIndex = 0;
$.each(this.args, function() {
argArray[argArrayIndex] = this.value;
argArrayIndex++;
});
console.log(argArray);
// hardcoded support for six arguments
errorObj.message = jQuery.i18n.prop(this.userMessageGlobalisationCode, argArray[0], argArray[1], argArray[2], argArray[3], argArray[4], argArray[5]);
errorObj.value = this.value; errorObj.value = this.value;
errorArray[arrayIndex] = errorObj; errorArray[arrayIndex] = errorObj;
@@ -182,7 +193,7 @@
return o; return o;
}; };
function popupDialogWithFormView(getUrl, postUrl, titleCode, templateSelector, width, height, saveSuccessFunction) { function popupDialogWithFormView(getUrl, postUrl, submitType, titleCode, templateSelector, width, height, saveSuccessFunction) {
var dialogDiv = $("<div id='dialog-form'></div>"); var dialogDiv = $("<div id='dialog-form'></div>");
var jqxhr = $.ajax({ var jqxhr = $.ajax({
url: getUrl, url: getUrl,
@@ -218,7 +229,7 @@
var jqxhr = $.ajax({ var jqxhr = $.ajax({
url: postUrl, url: postUrl,
type: 'POST', type: submitType,
contentType: 'application/json', contentType: 'application/json',
dataType: 'json', dataType: 'json',
data: newFormData, data: newFormData,
@@ -273,7 +284,6 @@
$('#addloanproduct').click(function(e) { $('#addloanproduct').click(function(e) {
var getUrl = 'http://localhost:8085/mifosng-provider/api/v1/loanproducts/template'; var getUrl = 'http://localhost:8085/mifosng-provider/api/v1/loanproducts/template';
var postUrl = 'http://localhost:8085/mifosng-provider/api/v1/loanproducts'; var postUrl = 'http://localhost:8085/mifosng-provider/api/v1/loanproducts';
//var url = '${rootContext}portfolio/product/loan/new';
var templateSelector = "#productFormTemplate"; var templateSelector = "#productFormTemplate";
var width = 800; var width = 800;
var height = 550; var height = 550;
@@ -283,13 +293,13 @@
refreshLoanProductsView(); refreshLoanProductsView();
} }
popupDialogWithFormView(getUrl, postUrl, "dialog.title.add.loan.product", templateSelector, width, height, saveSuccessFunction); popupDialogWithFormView(getUrl, postUrl, 'POST', "dialog.title.add.loan.product", templateSelector, width, height, saveSuccessFunction);
e.preventDefault(); e.preventDefault();
}); });
function refreshLoanProductsView() { function refreshLoanProductsView() {
var jqxhr = $.ajax({ var jqxhr = $.ajax({
url: '${allLoanProductsUrl}', url: 'http://localhost:8085/mifosng-provider/api/v1/loanproducts', //'${allLoanProductsUrl}',
type: 'GET', type: 'GET',
contentType: 'application/json', contentType: 'application/json',
dataType: 'json', dataType: 'json',
@@ -297,7 +307,7 @@
success: function(data, textStatus, jqXHR) { success: function(data, textStatus, jqXHR) {
var productlistParent = new Object(); var productlistParent = new Object();
productlistParent.items = data; productlistParent.items = data.products;
var productListHtml = $("#productListTemplate").render(productlistParent); var productListHtml = $("#productListTemplate").render(productlistParent);
$("#listplaceholder").html(productListHtml); $("#listplaceholder").html(productListHtml);
@@ -305,7 +315,8 @@
$("a.editproduct").click( function(e) { $("a.editproduct").click( function(e) {
var linkId = this.id; var linkId = this.id;
var productId = linkId.replace("editproduct", ""); var productId = linkId.replace("editproduct", "");
var url = '${rootContext}portfolio/product/loan/' + productId; var getUrl = 'http://localhost:8085/mifosng-provider/api/v1/loanproducts/' + productId;
var putUrl = 'http://localhost:8085/mifosng-provider/api/v1/loanproducts/' + productId;
var templateSelector = "#productFormTemplate"; var templateSelector = "#productFormTemplate";
var width = 800; var width = 800;
@@ -316,7 +327,7 @@
refreshLoanProductsView(); refreshLoanProductsView();
} }
popupDialogWithFormView(url, "dialog.title.product.details", templateSelector, width, height, saveSuccessFunction); popupDialogWithFormView(getUrl, putUrl, 'PUT', "dialog.title.product.details", templateSelector, width, height, saveSuccessFunction);
e.preventDefault(); e.preventDefault();
}); });
@@ -374,7 +385,7 @@
refreshOfficesView(); refreshOfficesView();
} }
popupDialogWithFormView(url, "dialog.title.add.office", templateSelector, width, height, saveSuccessFunction); popupDialogWithFormView(getUrl, postUrl, 'POST', "dialog.title.add.office", templateSelector, width, height, saveSuccessFunction);
e.preventDefault(); e.preventDefault();
}); });
@@ -399,7 +410,9 @@
$("a.edit").click( function(e) { $("a.edit").click( function(e) {
var linkId = this.id; var linkId = this.id;
var entityId = linkId.replace("edit", ""); var entityId = linkId.replace("edit", "");
var url = '${rootContext}org/office/' + entityId; var getUrl = 'http://localhost:8085/mifosng-provider/api/v1/offices/' + entityId;
var putUrl = 'http://localhost:8085/mifosng-provider/api/v1/offices/' + entityId;
var templateSelector = "#officeFormTemplate"; var templateSelector = "#officeFormTemplate";
var width = 600; var width = 600;
var height = 400; var height = 400;
@@ -409,7 +422,7 @@
refreshOfficesView(); refreshOfficesView();
} }
popupDialogWithFormView(url, "dialog.title.office.details", templateSelector, width, height, saveSuccessFunction); popupDialogWithFormView(getUrl, putUrl, 'PUT', "dialog.title.office.details", templateSelector, width, height, saveSuccessFunction);
e.preventDefault(); e.preventDefault();
}); });
@@ -444,7 +457,8 @@
// currency configuration // currency configuration
$('#editconfiguration').click(function(e) { $('#editconfiguration').click(function(e) {
var url = '${rootContext}org/configuration/edit'; var getUrl = 'http://localhost:8085/mifosng-provider/api/v1/configurations/currency';
var putUrl = 'http://localhost:8085/mifosng-provider/api/v1/configurations/currency';
var templateSelector = "#configurationFormTemplate"; var templateSelector = "#configurationFormTemplate";
var width = 900; var width = 900;
var height = 400; var height = 400;
@@ -453,7 +467,7 @@
$("#dialog-form").dialog("close"); $("#dialog-form").dialog("close");
} }
popupDialogWithFormView(url, "dialog.title.configuration.currencies", templateSelector, width, height, saveSuccessFunction); popupDialogWithFormView(getUrl, putUrl, 'PUT', "dialog.title.configuration.currencies", templateSelector, width, height, saveSuccessFunction);
e.preventDefault(); e.preventDefault();
}); });
@@ -34,8 +34,8 @@
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend><spring:message code="form.legend.loan.product.currency"/></legend> <legend><spring:message code="form.legend.loan.product.currency"/></legend>
<label for="selectedCurrency"><spring:message code="form.label.loan.product.currency"/></label> <label for="currencyCode"><spring:message code="form.label.loan.product.currency"/></label>
<select id="selectedCurrency" name="selectedCurrency" title="" style="width: 300px;"> <select id="currencyCode" name="currencyCode" title="" style="width: 300px;">
{{#each possibleCurrencies}} {{#each possibleCurrencies}}
{{#if $parent.parent.data.principalMoney.currencyCode===code}} {{#if $parent.parent.data.principalMoney.currencyCode===code}}
<option value="{{=code}}" selected="selected">{{=name}}</option> <option value="{{=code}}" selected="selected">{{=name}}</option>
@@ -44,8 +44,8 @@
{{/if}} {{/if}}
{{/each}} {{/each}}
</select> </select>
<label for="selectedDigitsAfterDecimal"><spring:message code="form.label.loan.product.decimalplaces"/></label> <label for="digitsAfterDecimal"><spring:message code="form.label.loan.product.decimalplaces"/></label>
<input id="selectedDigitsAfterDecimal" name="selectedDigitsAfterDecimal" title="" style="width: 300px;" value="{{=$ctx.number(principalMoney.currencyDigitsAfterDecimal)}}" /> <input id="digitsAfterDecimal" name="digitsAfterDecimal" title="" style="width: 300px;" value="{{=$ctx.number(principalMoney.currencyDigitsAfterDecimal)}}" />
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend><spring:message code="form.legend.loan.product.loan.terms"/></legend> <legend><spring:message code="form.legend.loan.product.loan.terms"/></legend>
@@ -57,15 +57,15 @@
<tr> <tr>
<td><spring:message code="form.label.loan.product.loan.amount"/></td> <td><spring:message code="form.label.loan.product.loan.amount"/></td>
<td> <td>
<input id="amount" name="amount" title="" style="width: 125px;" value="{{=$ctx.money(principalMoney)}}" /> <input id="principal" name="principal" title="" style="width: 125px;" value="{{=$ctx.money(principalMoney)}}" />
</td> </td>
</tr> </tr>
<tr> <tr>
<td><spring:message code="form.label.loan.product.repaidevery"/></td> <td><spring:message code="form.label.loan.product.repaidevery"/></td>
<td> <td>
<input id="repaidEvery" name="repaidEvery" title="" style="width: 50px;" value="{{=$ctx.number(repaidEvery)}}"/> <input id="repaymentEvery" name="repaymentEvery" title="" style="width: 50px;" value="{{=$ctx.number(repaidEvery)}}"/>
<select id="selectedRepaymentFrequencyOption" name="selectedRepaymentFrequencyOption" title="" style="width: 121px;"> <select id="repaymentFrequency" name="repaymentFrequency" title="" style="width: 121px;">
{{#each repaymentFrequencyOptions}} {{#each repaymentFrequencyOptions}}
{{#if $ctx.number($parent.parent.data.repaymentPeriodFrequency)===$ctx.number(id)}} {{#if $ctx.number($parent.parent.data.repaymentPeriodFrequency)===$ctx.number(id)}}
<option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option> <option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option>
@@ -89,9 +89,9 @@
<tr> <tr>
<td><spring:message code="form.label.loan.product.nominal.interestrate"/></td> <td><spring:message code="form.label.loan.product.nominal.interestrate"/></td>
<td> <td>
<input id="nominalInterestRate" name="nominalInterestRate" title="" style="width: 70px;" value="{{=$ctx.decimal(interestRatePerPeriod, 4)}}" /> <input id="interestRatePerPeriod" name="interestRatePerPeriod" title="" style="width: 70px;" value="{{=$ctx.decimal(interestRatePerPeriod, 4)}}" />
<select id="selectedInterestFrequencyOption" name="selectedInterestFrequencyOption" title="" style="width: 139px;"> <select id="interestRateFrequencyMethod" name="interestRateFrequencyMethod" title="" style="width: 139px;">
{{#each interestFrequencyOptions}} {{#each interestFrequencyOptions}}
{{#if $ctx.number($parent.parent.data.interestRatePeriod)===$ctx.number(id)}} {{#if $ctx.number($parent.parent.data.interestRatePeriod)===$ctx.number(id)}}
<option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option> <option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option>
@@ -105,7 +105,7 @@
<tr> <tr>
<td><spring:message code="form.label.loan.product.amortization"/></td> <td><spring:message code="form.label.loan.product.amortization"/></td>
<td> <td>
<select id="selectedAmortizationMethodOption" name="selectedAmortizationMethodOption" title="" style="width: 220px;"> <select id="amortizationMethod" name="amortizationMethod" title="" style="width: 220px;">
{{#each possibleAmortizationOptions}} {{#each possibleAmortizationOptions}}
{{#if $ctx.number($parent.parent.data.amortizationMethod)===$ctx.number(id)}} {{#if $ctx.number($parent.parent.data.amortizationMethod)===$ctx.number(id)}}
<option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option> <option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option>
@@ -119,7 +119,7 @@
<tr> <tr>
<td><spring:message code="form.label.loan.product.interest.method"/></td> <td><spring:message code="form.label.loan.product.interest.method"/></td>
<td> <td>
<select id="selectedInterestMethodOption" name="selectedInterestMethodOption" title="" style="width: 220px;"> <select id="interestMethod" name="interestMethod" title="" style="width: 220px;">
{{#each possibleInterestOptions}} {{#each possibleInterestOptions}}
{{#if $ctx.number($parent.parent.data.interestMethod)===$ctx.number(id)}} {{#if $ctx.number($parent.parent.data.interestMethod)===$ctx.number(id)}}
<option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option> <option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option>
@@ -133,7 +133,7 @@
<tr> <tr>
<td><spring:message code="form.label.loan.product.interest.rate.calcutated.in.period"/></td> <td><spring:message code="form.label.loan.product.interest.rate.calcutated.in.period"/></td>
<td> <td>
<select id="interestRateCalculatedInPeriod" name="interestRateCalculatedInPeriod" title="" style="width: 220px;"> <select id="interestCalculationPeriodMethod" name="interestCalculationPeriodMethod" title="" style="width: 220px;">
{{#each possibleInterestRateCalculatedInPeriodOptions}} {{#each possibleInterestRateCalculatedInPeriodOptions}}
{{#if $ctx.number($parent.parent.data.interestRateCalculatedInPeriod)===$ctx.number(id)}} {{#if $ctx.number($parent.parent.data.interestRateCalculatedInPeriod)===$ctx.number(id)}}
<option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option> <option value="{{=$ctx.number(id)}}" selected="selected">{{=value}}</option>
@@ -147,7 +147,7 @@
<tr> <tr>
<td><spring:message code="form.label.loan.product.arrears.tolerance"/></td> <td><spring:message code="form.label.loan.product.arrears.tolerance"/></td>
<td> <td>
<input id="inArrearsTolerance" name="inArrearsTolerance" title="" style="width: 215px;" value="{{=$ctx.money(inArrearsTolerance)}}" /> <input id="inArrearsToleranceAmount" name="inArrearsToleranceAmount" title="" style="width: 215px;" value="{{=$ctx.money(inArrearsTolerance)}}" />
</td> </td>
</tr> </tr>
</table> </table>
@@ -240,10 +240,13 @@
{{/if}} {{/if}}
{{/each}} {{/each}}
</select> </select>
{{#else}}
<input type="hidden" id="rootOffice" name="rootOffice" value="true" />
{{/if}} {{/if}}
<label for="openingDate"><spring:message code="form.label.office.openedon"/></label> <input type="hidden" id="dateFormat" name="dateFormat" value="dd MMMM yyyy" />
<input id="openingDate" name="openingDate" title="" type="text" value="{{=$ctx.globalDate(openingDate)}}" size="75" class="datepickerfield" /> <label for="openingDateFormatted"><spring:message code="form.label.office.openedon"/></label>
<input id="openingDateFormatted" name="openingDateFormatted" title="" type="text" value="{{=$ctx.globalDate(openingDate)}}" size="75" class="datepickerfield" />
<label for="externalId"><spring:message code="form.label.office.externalid"/></label> <label for="externalId"><spring:message code="form.label.office.externalid"/></label>
<input id="externalId" name="externalId" title="" type="text" value="{{=externalId}}" size="75"/> <input id="externalId" name="externalId" title="" type="text" value="{{=externalId}}" size="75"/>
@@ -10,16 +10,13 @@ import org.mifosng.data.ClientDataWithAccountsData;
import org.mifosng.data.CurrencyData; import org.mifosng.data.CurrencyData;
import org.mifosng.data.EnumOptionReadModel; import org.mifosng.data.EnumOptionReadModel;
import org.mifosng.data.LoanAccountData; import org.mifosng.data.LoanAccountData;
import org.mifosng.data.LoanProductData;
import org.mifosng.data.LoanRepaymentData; import org.mifosng.data.LoanRepaymentData;
import org.mifosng.data.NewLoanWorkflowStepOneData; import org.mifosng.data.NewLoanWorkflowStepOneData;
import org.mifosng.data.NoteData; import org.mifosng.data.NoteData;
import org.mifosng.data.OfficeData;
import org.mifosng.data.OrganisationReadModel; import org.mifosng.data.OrganisationReadModel;
import org.mifosng.data.PermissionData; import org.mifosng.data.PermissionData;
import org.mifosng.data.RoleData; import org.mifosng.data.RoleData;
import org.mifosng.data.reports.GenericResultset; import org.mifosng.data.reports.GenericResultset;
import org.springframework.security.access.prepost.PreAuthorize;
public interface ReadPlatformService { public interface ReadPlatformService {
@@ -27,8 +24,6 @@ public interface ReadPlatformService {
Collection<ClientData> retrieveAllIndividualClients(); Collection<ClientData> retrieveAllIndividualClients();
Collection<OfficeData> retrieveAllOffices();
ClientData retrieveIndividualClient(Long clientId); ClientData retrieveIndividualClient(Long clientId);
ClientDataWithAccountsData retrieveClientAccountDetails(Long clientId); ClientDataWithAccountsData retrieveClientAccountDetails(Long clientId);
@@ -43,28 +38,10 @@ public interface ReadPlatformService {
LoanRepaymentData retrieveLoanRepaymentDetails(Long loanId, Long repaymentId); LoanRepaymentData retrieveLoanRepaymentDetails(Long loanId, Long repaymentId);
Collection<LoanProductData> retrieveAllLoanProducts();
List<CurrencyData> retrieveAllowedCurrencies(); List<CurrencyData> retrieveAllowedCurrencies();
List<CurrencyData> retrieveAllPlatformCurrencies(); List<CurrencyData> retrieveAllPlatformCurrencies();
List<EnumOptionReadModel> retrieveLoanAmortizationMethodOptions();
List<EnumOptionReadModel> retrieveLoanInterestMethodOptions();
List<EnumOptionReadModel> retrieveLoanInterestRateCalculatedInPeriodOptions();
List<EnumOptionReadModel> retrieveRepaymentFrequencyOptions();
List<EnumOptionReadModel> retrieveInterestFrequencyOptions();
LoanProductData retrieveLoanProduct(Long productId);
LoanProductData retrieveNewLoanProductDetails();
OfficeData retrieveOffice(Long officeId);
Collection<AppUserData> retrieveAllUsers(); Collection<AppUserData> retrieveAllUsers();
AppUserData retrieveNewUserDetails(); AppUserData retrieveNewUserDetails();
@@ -5,14 +5,12 @@ import static org.mifosng.platform.Specifications.loanTransactionsThatMatch;
import static org.mifosng.platform.Specifications.loansThatMatch; import static org.mifosng.platform.Specifications.loansThatMatch;
import static org.mifosng.platform.Specifications.usersThatMatch; import static org.mifosng.platform.Specifications.usersThatMatch;
import java.math.BigDecimal;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -53,12 +51,11 @@ import org.mifosng.platform.currency.domain.ApplicationCurrencyRepository;
import org.mifosng.platform.currency.domain.Money; import org.mifosng.platform.currency.domain.Money;
import org.mifosng.platform.exceptions.PlatformResourceNotFoundException; import org.mifosng.platform.exceptions.PlatformResourceNotFoundException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException; import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.loan.domain.AmortizationMethod;
import org.mifosng.platform.loan.domain.Loan; import org.mifosng.platform.loan.domain.Loan;
import org.mifosng.platform.loan.domain.LoanRepository; import org.mifosng.platform.loan.domain.LoanRepository;
import org.mifosng.platform.loan.domain.LoanTransaction; import org.mifosng.platform.loan.domain.LoanTransaction;
import org.mifosng.platform.loan.domain.LoanTransactionRepository; import org.mifosng.platform.loan.domain.LoanTransactionRepository;
import org.mifosng.platform.loan.domain.PeriodFrequencyType; import org.mifosng.platform.loanproduct.service.LoanProductReadPlatformService;
import org.mifosng.platform.organisation.domain.Organisation; import org.mifosng.platform.organisation.domain.Organisation;
import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUser;
import org.mifosng.platform.user.domain.AppUserRepository; import org.mifosng.platform.user.domain.AppUserRepository;
@@ -91,14 +88,18 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
private final AppUserRepository appUserRepository; private final AppUserRepository appUserRepository;
private final RoleRepository roleRepository; private final RoleRepository roleRepository;
private final LoanProductReadPlatformService loanProductReadPlatformService;
@Autowired @Autowired
public ReadPlatformServiceImpl(final DataSource dataSource, public ReadPlatformServiceImpl(final LoanProductReadPlatformService loanProductReadPlatformService,
final DataSource dataSource,
final ClientRepository clientRepository, final ClientRepository clientRepository,
final LoanRepository loanRepository, final LoanRepository loanRepository,
final LoanTransactionRepository loanTransactionRepository, final LoanTransactionRepository loanTransactionRepository,
final ApplicationCurrencyRepository applicationCurrencyRepository, final ApplicationCurrencyRepository applicationCurrencyRepository,
final AppUserRepository appUserRepository, final AppUserRepository appUserRepository,
final RoleRepository roleRepository) { final RoleRepository roleRepository) {
this.loanProductReadPlatformService = loanProductReadPlatformService;
this.loanTransactionRepository = loanTransactionRepository; this.loanTransactionRepository = loanTransactionRepository;
this.applicationCurrencyRepository = applicationCurrencyRepository; this.applicationCurrencyRepository = applicationCurrencyRepository;
this.appUserRepository = appUserRepository; this.appUserRepository = appUserRepository;
@@ -360,47 +361,6 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
} }
} }
@Override
public Collection<OfficeData> retrieveAllOffices() {
return retrieveOffices();
}
@Override
public OfficeData retrieveOffice(final Long officeId) {
try {
AppUser currentUser = extractAuthenticatedUser();
OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema()
+ " where o.org_id = ? and o.id = ?";
OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql,
rm, new Object[] { currentUser.getOrganisation().getId(),
officeId });
List<OfficeData> allowedParents = new ArrayList<OfficeData>();
if (StringUtils.isNotBlank(selectedOffice.getParentName())) {
Collection<OfficeData> allOffices = retrieveAllOffices();
for (OfficeData office : allOffices) {
if (!office.getId().equals(selectedOffice.getId())) {
allowedParents.add(office);
}
}
}
selectedOffice.setAllowedParents(allowedParents);
return selectedOffice;
} catch (EmptyResultDataAccessException e) {
throw new PlatformResourceNotFoundException("error.msg.office.id.invalid", "Office with identifier {0} does not exist", officeId);
}
}
@Override @Override
public ClientData retrieveIndividualClient(final Long clientId) { public ClientData retrieveIndividualClient(final Long clientId) {
@@ -571,12 +531,12 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
workflowData.setOrganisationName(currentUser.getOrganisation() workflowData.setOrganisationName(currentUser.getOrganisation()
.getName()); .getName());
Collection<LoanProductData> loanProducts = retrieveAllLoanProducts(); Collection<LoanProductData> loanProducts = this.loanProductReadPlatformService.retrieveAllLoanProducts();
workflowData.setAllowedProducts(new ArrayList<LoanProductData>( workflowData.setAllowedProducts(new ArrayList<LoanProductData>(
loanProducts)); loanProducts));
if (loanProducts.size() == 1) { if (loanProducts.size() == 1) {
LoanProductData selectedProduct = retrieveLoanProduct(workflowData.getAllowedProducts().get(0).getId()); LoanProductData selectedProduct = this.loanProductReadPlatformService.retrieveLoanProduct(workflowData.getAllowedProducts().get(0).getId());
workflowData.setProductId(selectedProduct.getId()); workflowData.setProductId(selectedProduct.getId());
workflowData.setProductName(selectedProduct.getName()); workflowData.setProductName(selectedProduct.getName());
@@ -597,10 +557,10 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
} }
private LoanProductData findLoanProductById(Collection<LoanProductData> loanProducts, Long productId) { private LoanProductData findLoanProductById(Collection<LoanProductData> loanProducts, Long productId) {
LoanProductData match = retrieveNewLoanProductDetails(); LoanProductData match = this.loanProductReadPlatformService.retrieveNewLoanProductDetails();
for (LoanProductData loanProductData : loanProducts) { for (LoanProductData loanProductData : loanProducts) {
if (loanProductData.getId().equals(productId)) { if (loanProductData.getId().equals(productId)) {
match = retrieveLoanProduct(loanProductData.getId()); match = this.loanProductReadPlatformService.retrieveLoanProduct(loanProductData.getId());
break; break;
} }
} }
@@ -707,165 +667,6 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
tolerance, loanData, waiveAllowed, interestRebateOwed); tolerance, loanData, waiveAllowed, interestRebateOwed);
} }
@Override
public Collection<LoanProductData> retrieveAllLoanProducts() {
AppUser currentUser = extractAuthenticatedUser();
List<CurrencyData> allowedCurrencies = retrieveAllowedCurrencies();
LoanProductMapper rm = new LoanProductMapper(allowedCurrencies);
String sql = "select " + rm.loanProductSchema()
+ " where lp.org_id = ?";
return this.jdbcTemplate.query(sql, rm, new Object[] { currentUser
.getOrganisation().getId() });
}
protected static final class LoanProductMapper implements
RowMapper<LoanProductData> {
private final List<CurrencyData> allowedCurrencies;
public LoanProductMapper(List<CurrencyData> allowedCurrencies) {
this.allowedCurrencies = allowedCurrencies;
}
public String loanProductSchema() {
return "lp.id as id, lp.name as name, lp.description as description, lp.flexible_repayment_schedule as isFlexible, lp.interest_rebate as isInterestRebateAllowed, "
+ "lp.principal_amount as principal, lp.currency_code as currencyCode, lp.currency_digits as currencyDigits, "
+ "lp.nominal_interest_rate_per_period as interestRatePerPeriod, lp.interest_period_frequency_enum as interestRatePerPeriodFreq, "
+ "lp.annual_nominal_interest_rate as annualInterestRate, lp.interest_method_enum as interestMethod, lp.interest_calculated_in_period_enum as interestCalculationInPeriodMethod,"
+ "lp.repay_every as repaidEvery, lp.repayment_period_frequency_enum as repaymentPeriodFrequency, lp.number_of_repayments as numberOfRepayments, "
+ "lp.amortization_method_enum as amortizationMethod, lp.arrearstolerance_amount as tolerance, "
+ "lp.created_date as createdon, lp.lastmodified_date as modifiedon "
+ " from portfolio_product_loan lp";
}
@Override
public LoanProductData mapRow(final ResultSet rs, final int rowNum)
throws SQLException {
Long id = rs.getLong("id");
String name = rs.getString("name");
String description = rs.getString("description");
boolean isFlexible = rs.getBoolean("isFlexible");
boolean isInterestRebateAllowed = rs
.getBoolean("isInterestRebateAllowed");
String currencyCode = rs.getString("currencyCode");
int currencyDigits = rs.getInt("currencyDigits");
CurrencyData currencyData = findCurrencyByCode(currencyCode, allowedCurrencies);
currencyData.setDecimalPlaces(currencyDigits);
BigDecimal principal = rs.getBigDecimal("principal");
BigDecimal tolerance = rs.getBigDecimal("tolerance");
MoneyData principalMoney = MoneyData.of(currencyData, principal);
MoneyData toleranceMoney = MoneyData.of(currencyData, tolerance);
BigDecimal interestRatePerPeriod = rs
.getBigDecimal("interestRatePerPeriod");
int interestRatePeriod = rs.getInt("interestRatePerPeriodFreq");
BigDecimal annualInterestRate = rs
.getBigDecimal("annualInterestRate");
int interestMethod = rs.getInt("interestMethod");
int interestCalculationInPeriodMethod = rs.getInt("interestCalculationInPeriodMethod");
int repaidEvery = rs.getInt("repaidEvery");
int repaymentFrequency = rs.getInt("repaymentPeriodFrequency");
int numberOfRepayments = rs.getInt("numberOfRepayments");
int amortizationMethod = rs.getInt("amortizationMethod");
DateTime createdOn = new DateTime(rs.getDate("createdOn"));
DateTime lastModifedOn = new DateTime(rs.getDate("modifiedon"));
return new LoanProductData(id, name, description, isFlexible,
isInterestRebateAllowed, principalMoney,
interestRatePerPeriod, interestRatePeriod,
annualInterestRate, interestMethod, interestCalculationInPeriodMethod,
repaidEvery,
repaymentFrequency, numberOfRepayments, amortizationMethod,
toleranceMoney, createdOn, lastModifedOn);
}
private CurrencyData findCurrencyByCode(String currencyCode, List<CurrencyData> allowedCurrencies) {
CurrencyData match = null;
for (CurrencyData currencyData : allowedCurrencies) {
if (currencyData.getCode().equalsIgnoreCase(currencyCode)) {
match = currencyData;
break;
}
}
return match;
}
}
@Override
public LoanProductData retrieveLoanProduct(final Long loanProductId) {
// TODO - switch back to retrieve all allowed organisation currencies
List<CurrencyData> allowedCurrencies = retrieveAllPlatformCurrencies();
LoanProductMapper rm = new LoanProductMapper(allowedCurrencies);
String sql = "select " + rm.loanProductSchema() + " where lp.id = ?";
LoanProductData productData = this.jdbcTemplate.queryForObject(sql, rm,
new Object[] { loanProductId });
populateProductDataWithDropdownOptions(productData);
return productData;
}
private void populateProductDataWithDropdownOptions(
LoanProductData productData) {
List<CurrencyData> possibleCurrencies = retrieveAllowedCurrencies();
List<EnumOptionReadModel> possibleAmortizationOptions = retrieveLoanAmortizationMethodOptions();
List<EnumOptionReadModel> possibleInterestOptions = retrieveLoanInterestMethodOptions();
List<EnumOptionReadModel> possibleInterestRateCalculatedInPeriodOptions = retrieveLoanInterestRateCalculatedInPeriodOptions();
List<EnumOptionReadModel> repaymentFrequencyOptions = retrieveRepaymentFrequencyOptions();
List<EnumOptionReadModel> interestFrequencyOptions = retrieveInterestFrequencyOptions();
productData.setPossibleCurrencies(possibleCurrencies);
productData.setPossibleAmortizationOptions(possibleAmortizationOptions);
productData.setPossibleInterestOptions(possibleInterestOptions);
productData.setPossibleInterestRateCalculatedInPeriodOptions(possibleInterestRateCalculatedInPeriodOptions);
productData.setRepaymentFrequencyOptions(repaymentFrequencyOptions);
productData.setInterestFrequencyOptions(interestFrequencyOptions);
}
@Override
public LoanProductData retrieveNewLoanProductDetails() {
LoanProductData productData = new LoanProductData();
populateProductDataWithDropdownOptions(productData);
if (productData.getPossibleCurrencies().size() >= 1) {
CurrencyData currency = productData.getPossibleCurrencies().get(0);
MoneyData zero = MoneyData.zero(currency);
productData.setPrincipalMoney(zero);
productData.setInArrearsTolerance(zero);
}
productData.setAmortizationMethod(Integer.valueOf(1));
productData.setInterestMethod(Integer.valueOf(0));
productData.setRepaymentPeriodFrequency(2);
productData.setInterestRatePeriod(2);
productData.setInterestRateCalculatedInPeriod(1);
productData.setRepaidEvery(1);
productData.setNumberOfRepayments(0);
return productData;
}
@Override @Override
public List<CurrencyData> retrieveAllowedCurrencies() { public List<CurrencyData> retrieveAllowedCurrencies() {
@@ -907,70 +708,6 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
} }
} }
@Override
public List<EnumOptionReadModel> retrieveLoanAmortizationMethodOptions() {
EnumOptionReadModel equalInstallments = new EnumOptionReadModel(
"Equal installments", AmortizationMethod.EQUAL_INSTALLMENTS
.getValue().longValue());
EnumOptionReadModel equalPrinciplePayments = new EnumOptionReadModel(
"Equal principle payments", AmortizationMethod.EQUAL_PRINCIPAL
.getValue().longValue());
List<EnumOptionReadModel> allowedAmortizationMethods = Arrays.asList(
equalInstallments, equalPrinciplePayments);
return allowedAmortizationMethods;
}
@Override
public List<EnumOptionReadModel> retrieveLoanInterestMethodOptions() {
EnumOptionReadModel interestRateCalculationMethod2 = new EnumOptionReadModel(
"Declining Balance", Long.valueOf(0));
EnumOptionReadModel interestRateCalculationMethod1 = new EnumOptionReadModel(
"Flat", Long.valueOf(1));
List<EnumOptionReadModel> allowedRepaymentScheduleCalculationMethods = Arrays
.asList(interestRateCalculationMethod2,
interestRateCalculationMethod1);
return allowedRepaymentScheduleCalculationMethods;
}
@Override
public List<EnumOptionReadModel> retrieveLoanInterestRateCalculatedInPeriodOptions() {
EnumOptionReadModel option1 = new EnumOptionReadModel("Daily", Long.valueOf(0));
EnumOptionReadModel option2 = new EnumOptionReadModel("Same as repayment period", Long.valueOf(1));
List<EnumOptionReadModel> allowedOptions = Arrays.asList(option1,option2);
return allowedOptions;
}
@Override
public List<EnumOptionReadModel> retrieveRepaymentFrequencyOptions() {
EnumOptionReadModel frequency1 = new EnumOptionReadModel("Days",
Long.valueOf(0));
EnumOptionReadModel frequency2 = new EnumOptionReadModel("Weeks",
Long.valueOf(1));
EnumOptionReadModel frequency3 = new EnumOptionReadModel("Months",
Long.valueOf(2));
List<EnumOptionReadModel> repaymentFrequencyOptions = Arrays.asList(
frequency1, frequency2, frequency3);
return repaymentFrequencyOptions;
}
@Override
public List<EnumOptionReadModel> retrieveInterestFrequencyOptions() {
// support for monthly and annual percentage rate (MPR) and (APR)
EnumOptionReadModel perMonth = new EnumOptionReadModel("Per month",
PeriodFrequencyType.MONTHS.getValue().longValue());
EnumOptionReadModel perYear = new EnumOptionReadModel("Per year",
PeriodFrequencyType.YEARS.getValue().longValue());
List<EnumOptionReadModel> repaymentFrequencyOptions = Arrays.asList(perMonth, perYear);
return repaymentFrequencyOptions;
}
@Override @Override
public Collection<AppUserData> retrieveAllUsers() { public Collection<AppUserData> retrieveAllUsers() {
@@ -4,17 +4,14 @@ import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.command.AdjustLoanTransactionCommand; import org.mifosng.data.command.AdjustLoanTransactionCommand;
import org.mifosng.data.command.ChangePasswordCommand; import org.mifosng.data.command.ChangePasswordCommand;
import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.EnrollClientCommand;
import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanStateTransitionCommand;
import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.LoanTransactionCommand;
import org.mifosng.data.command.NoteCommand; import org.mifosng.data.command.NoteCommand;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.RoleCommand;
import org.mifosng.data.command.SignupCommand; import org.mifosng.data.command.SignupCommand;
import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand;
import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanApprovalCommand;
import org.mifosng.data.command.UndoLoanDisbursalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand;
import org.mifosng.data.command.UpdateOrganisationCurrencyCommand;
import org.mifosng.data.command.UpdateUsernamePasswordCommand; import org.mifosng.data.command.UpdateUsernamePasswordCommand;
import org.mifosng.data.command.UserCommand; import org.mifosng.data.command.UserCommand;
import org.mifosng.platform.exceptions.InvalidSignupException; import org.mifosng.platform.exceptions.InvalidSignupException;
@@ -22,10 +19,6 @@ import org.springframework.security.access.prepost.PreAuthorize;
public interface WritePlatformService { public interface WritePlatformService {
Long createOffice(OfficeCommand command);
Long updateOffice(OfficeCommand command);
Long createUser(UserCommand command); Long createUser(UserCommand command);
Long updateUser(UserCommand command); Long updateUser(UserCommand command);
@@ -50,12 +43,6 @@ public interface WritePlatformService {
@PreAuthorize(value = "hasAnyRole('PORTFOLIO_MANAGEMENT_SUPER_USER_ROLE', 'CAN_ENROLL_NEW_CLIENT_ROLE')") @PreAuthorize(value = "hasAnyRole('PORTFOLIO_MANAGEMENT_SUPER_USER_ROLE', 'CAN_ENROLL_NEW_CLIENT_ROLE')")
Long enrollClient(EnrollClientCommand command); Long enrollClient(EnrollClientCommand command);
void updateOrganisationCurrencies(UpdateOrganisationCurrencyCommand command);
EntityIdentifier createLoanProduct(LoanProductCommand command);
EntityIdentifier updateLoanProduct(LoanProductCommand command);
@PreAuthorize(value = "hasAnyRole('PORTFOLIO_MANAGEMENT_SUPER_USER_ROLE', 'CAN_DELETE_LOAN_THAT_IS_SUBMITTED_AND_NOT_APPROVED')") @PreAuthorize(value = "hasAnyRole('PORTFOLIO_MANAGEMENT_SUPER_USER_ROLE', 'CAN_DELETE_LOAN_THAT_IS_SUBMITTED_AND_NOT_APPROVED')")
EntityIdentifier deleteLoan(Long loanId); EntityIdentifier deleteLoan(Long loanId);
@@ -2,7 +2,6 @@ package org.mifosng.platform;
import static org.mifosng.platform.Specifications.loansThatMatch; import static org.mifosng.platform.Specifications.loansThatMatch;
import static org.mifosng.platform.Specifications.officesThatMatch; import static org.mifosng.platform.Specifications.officesThatMatch;
import static org.mifosng.platform.Specifications.productThatMatches;
import static org.mifosng.platform.Specifications.rolesThatMatch; import static org.mifosng.platform.Specifications.rolesThatMatch;
import static org.mifosng.platform.Specifications.usersThatMatch; import static org.mifosng.platform.Specifications.usersThatMatch;
@@ -25,32 +24,26 @@ import org.mifosng.data.command.AdjustLoanTransactionCommand;
import org.mifosng.data.command.CalculateLoanScheduleCommand; import org.mifosng.data.command.CalculateLoanScheduleCommand;
import org.mifosng.data.command.ChangePasswordCommand; import org.mifosng.data.command.ChangePasswordCommand;
import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.EnrollClientCommand;
import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanStateTransitionCommand;
import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.LoanTransactionCommand;
import org.mifosng.data.command.NoteCommand; import org.mifosng.data.command.NoteCommand;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.RoleCommand;
import org.mifosng.data.command.SignupCommand; import org.mifosng.data.command.SignupCommand;
import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand;
import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanApprovalCommand;
import org.mifosng.data.command.UndoLoanDisbursalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand;
import org.mifosng.data.command.UpdateOrganisationCurrencyCommand;
import org.mifosng.data.command.UpdateUsernamePasswordCommand; import org.mifosng.data.command.UpdateUsernamePasswordCommand;
import org.mifosng.data.command.UserCommand; import org.mifosng.data.command.UserCommand;
import org.mifosng.platform.client.domain.Client; import org.mifosng.platform.client.domain.Client;
import org.mifosng.platform.client.domain.ClientRepository; import org.mifosng.platform.client.domain.ClientRepository;
import org.mifosng.platform.client.domain.Note; import org.mifosng.platform.client.domain.Note;
import org.mifosng.platform.client.domain.NoteRepository; import org.mifosng.platform.client.domain.NoteRepository;
import org.mifosng.platform.currency.domain.ApplicationCurrency;
import org.mifosng.platform.currency.domain.ApplicationCurrencyRepository;
import org.mifosng.platform.currency.domain.MonetaryCurrency; import org.mifosng.platform.currency.domain.MonetaryCurrency;
import org.mifosng.platform.currency.domain.Money; import org.mifosng.platform.currency.domain.Money;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException; import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.InvalidSignupException; import org.mifosng.platform.exceptions.InvalidSignupException;
import org.mifosng.platform.exceptions.NewDataValidationException; import org.mifosng.platform.exceptions.NewDataValidationException;
import org.mifosng.platform.exceptions.NoAuthorizationException; import org.mifosng.platform.exceptions.NoAuthorizationException;
import org.mifosng.platform.exceptions.PlatformDataIntegrityException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException; import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.infrastructure.BasicPasswordEncodablePlatformUser; import org.mifosng.platform.infrastructure.BasicPasswordEncodablePlatformUser;
import org.mifosng.platform.infrastructure.PlatformPasswordEncoder; import org.mifosng.platform.infrastructure.PlatformPasswordEncoder;
@@ -73,13 +66,11 @@ import org.mifosng.platform.loan.domain.LoanStatusRepository;
import org.mifosng.platform.loan.domain.LoanTransaction; import org.mifosng.platform.loan.domain.LoanTransaction;
import org.mifosng.platform.loan.domain.LoanTransactionRepository; import org.mifosng.platform.loan.domain.LoanTransactionRepository;
import org.mifosng.platform.loan.domain.PeriodFrequencyType; import org.mifosng.platform.loan.domain.PeriodFrequencyType;
import org.mifosng.platform.loanproduct.service.LoanProductCommandValidator;
import org.mifosng.platform.organisation.domain.Office; import org.mifosng.platform.organisation.domain.Office;
import org.mifosng.platform.organisation.domain.OfficeRepository; import org.mifosng.platform.organisation.domain.OfficeRepository;
import org.mifosng.platform.organisation.domain.Organisation; import org.mifosng.platform.organisation.domain.Organisation;
import org.mifosng.platform.organisation.domain.OrganisationCurrency; import org.mifosng.platform.organisation.domain.OrganisationCurrency;
import org.mifosng.platform.organisation.domain.OrganisationRepository; import org.mifosng.platform.organisation.domain.OrganisationRepository;
import org.mifosng.platform.organisation.service.OfficeCommandValidator;
import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUser;
import org.mifosng.platform.user.domain.AppUserRepository; import org.mifosng.platform.user.domain.AppUserRepository;
import org.mifosng.platform.user.domain.Permission; import org.mifosng.platform.user.domain.Permission;
@@ -88,8 +79,6 @@ import org.mifosng.platform.user.domain.PlatformUserRepository;
import org.mifosng.platform.user.domain.Role; import org.mifosng.platform.user.domain.Role;
import org.mifosng.platform.user.domain.RoleRepository; import org.mifosng.platform.user.domain.RoleRepository;
import org.mifosng.platform.user.domain.UserDomainService; import org.mifosng.platform.user.domain.UserDomainService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@@ -99,11 +88,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@Service @Service
public class WritePlatformServiceJpaRepositoryImpl implements public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformService {
WritePlatformService {
private final static Logger logger = LoggerFactory
.getLogger(WritePlatformServiceJpaRepositoryImpl.class);
private final OrganisationRepository organisationRepository; private final OrganisationRepository organisationRepository;
private final OfficeRepository officeRepository; private final OfficeRepository officeRepository;
@@ -111,7 +96,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements
private final PlatformUserRepository platformUserRepository; private final PlatformUserRepository platformUserRepository;
private final PlatformPasswordEncoder platformPasswordEncoder; private final PlatformPasswordEncoder platformPasswordEncoder;
private final ClientRepository clientRepository; private final ClientRepository clientRepository;
private final ApplicationCurrencyRepository applicationCurrencyRepository;
private final LoanProductRepository loanProductRepository; private final LoanProductRepository loanProductRepository;
private final LoanRepository loanRepository; private final LoanRepository loanRepository;
private final LoanStatusRepository loanStatusRepository; private final LoanStatusRepository loanStatusRepository;
@@ -131,7 +115,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements
final PlatformPasswordEncoder platformPasswordEncoder, final PlatformPasswordEncoder platformPasswordEncoder,
final ClientRepository clientRepository, final ClientRepository clientRepository,
final NoteRepository noteRepository, final NoteRepository noteRepository,
final ApplicationCurrencyRepository applicationCurrencyRepository,
final LoanProductRepository loanProductRepository, final LoanProductRepository loanProductRepository,
final LoanRepository loanRepository, final LoanRepository loanRepository,
final LoanTransactionRepository loanTransactionRepository, final LoanTransactionRepository loanTransactionRepository,
@@ -147,7 +130,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements
this.platformPasswordEncoder = platformPasswordEncoder; this.platformPasswordEncoder = platformPasswordEncoder;
this.clientRepository = clientRepository; this.clientRepository = clientRepository;
this.noteRepository = noteRepository; this.noteRepository = noteRepository;
this.applicationCurrencyRepository = applicationCurrencyRepository;
this.loanProductRepository = loanProductRepository; this.loanProductRepository = loanProductRepository;
this.loanRepository = loanRepository; this.loanRepository = loanRepository;
this.loanTransactionRepository = loanTransactionRepository; this.loanTransactionRepository = loanTransactionRepository;
@@ -330,94 +312,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements
return role.getId(); return role.getId();
} }
@Transactional
@Override
public Long createOffice(final OfficeCommand command) {
try {
AppUser currentUser = extractAuthenticatedUser();
OfficeCommandValidator validator = new OfficeCommandValidator(command.getName(), command.getParentId(), command.getOpeningDate(), command.getExternalId());
validator.validate();
Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getParentId());
Office office = Office.createNew(currentUser.getOrganisation(), parent, command.getName(), command.getOpeningDate(), command.getExternalId());
// pre save to generate id for use in office hierarchy
this.officeRepository.save(office);
office.generateHierarchy();
this.officeRepository.save(office);
return office.getId();
} catch (DataIntegrityViolationException dve) {
handleOfficeDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
@Transactional
@Override
public Long updateOffice(final OfficeCommand command) {
try {
AppUser currentUser = extractAuthenticatedUser();
OfficeCommandValidator validator = new OfficeCommandValidator(command.getName(), command.getParentId(), command.getOpeningDate(), command.getExternalId());
validator.validate();
Office office = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getId());
office.update(command.getName(), command.getExternalId(), command.getOpeningDate());
this.officeRepository.save(office);
return office.getId();
} catch (DataIntegrityViolationException dve) {
handleOfficeDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue is.
*/
private void handleOfficeDataIntegrityIssues(final OfficeCommand command, DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("externalid_org")) {
throw new PlatformDataIntegrityException("error.msg.office.duplicate.externalId", "Office with externalId {0} already exists", "externalId", command.getExternalId());
} else if (realCause.getMessage().contains("name_org")) {
throw new PlatformDataIntegrityException("error.msg.office.duplicate.name", "Office with name {0} already exists", "name", command.getName());
}
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.office.unknown.data.integrity.issue", "Unknown data integrity issue with resource.");
}
/*
* used to restrict modifying operations to office that are either the users office or lower (child) in the office hierarchy
*/
private Office validateUserPriviledgeOnOfficeAndRetrieve(AppUser currentUser, Long officeId) {
Office userOffice = this.officeRepository.findOne(officesThatMatch(currentUser.getOrganisation(), currentUser.getOffice().getId()));
if (userOffice.doesNotHaveAnOfficeInHierarchyWithId(officeId)) {
ErrorResponse error = new ErrorResponse("error.msg.office.not.authorized", "id", officeId.toString());
throw new ApplicationDomainRuleException(Arrays.asList(error), "Errors exist.");
}
Office officeToReturn = userOffice;
if (!userOffice.identifiedBy(officeId)) {
officeToReturn = this.officeRepository.findOne(officesThatMatch(currentUser.getOrganisation(), officeId));
}
return officeToReturn;
}
@Transactional @Transactional
@Override @Override
public Long signup(final SignupCommand command) { public Long signup(final SignupCommand command) {
@@ -442,75 +336,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements
} }
} }
@Transactional
@Override
public EntityIdentifier createLoanProduct(final LoanProductCommand command) {
AppUser currentUser = extractAuthenticatedUser();
LoanProductCommandValidator validator = new LoanProductCommandValidator();
validator.validateForCreate(command);
// assemble LoanProduct from data
InterestMethod interestMethod = InterestMethod.fromInt(command.getInterestMethod());
InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.fromInt(command.getInterestCalculationPeriodMethod());
AmortizationMethod amortizationMethod = AmortizationMethod.fromInt(command.getAmortizationMethod());
PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType
.fromInt(command.getRepaymentFrequency());
PeriodFrequencyType interestFrequencyType = PeriodFrequencyType
.fromInt(command.getInterestRateFrequencyMethod());
MonetaryCurrency currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
// apr calculator
BigDecimal annualInterestRate = BigDecimal.ZERO;
switch (interestFrequencyType) {
case DAYS:
break;
case WEEKS:
annualInterestRate = command.getInterestRatePerPeriod().multiply(BigDecimal.valueOf(52));
break;
case MONTHS:
annualInterestRate = command.getInterestRatePerPeriod().multiply(BigDecimal.valueOf(12));
break;
case YEARS:
annualInterestRate = command.getInterestRatePerPeriod().multiply(BigDecimal.valueOf(1));
break;
case INVALID:
break;
}
LoanProduct loanproduct = new LoanProduct(currentUser.getOrganisation(), command.getName(), command.getDescription(),
currency, command.getPrincipal(),
command.getInterestRatePerPeriod(), interestFrequencyType, annualInterestRate, interestMethod, interestCalculationPeriodMethod,
command.getRepaymentEvery(), repaymentFrequencyType, command.getNumberOfRepayments(), amortizationMethod, command.getInArrearsToleranceAmount(),
command.isFlexibleRepaymentSchedule(), command.isInterestRebateAllowed());
this.loanProductRepository.save(loanproduct);
return new EntityIdentifier(loanproduct.getId());
}
@Transactional
@Override
public EntityIdentifier updateLoanProduct(LoanProductCommand command) {
AppUser currentUser = extractAuthenticatedUser();
LoanProductCommandValidator validator = new LoanProductCommandValidator();
validator.validateForUpdate(command);
LoanProduct product = this.loanProductRepository.findOne(productThatMatches(currentUser.getOrganisation(), command.getId()));
product.update(command);
this.loanProductRepository.save(product);
return new EntityIdentifier(Long.valueOf(product.getId()));
}
@Transactional @Transactional
@Override @Override
public void updateUsernamePasswordOnFirstTimeLogin(final UpdateUsernamePasswordCommand command) { public void updateUsernamePasswordOnFirstTimeLogin(final UpdateUsernamePasswordCommand command) {
@@ -565,35 +390,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements
return newClient.getId(); return newClient.getId();
} }
@Transactional
@Override
public void updateOrganisationCurrencies(final UpdateOrganisationCurrencyCommand command) {
AppUser currentUser = extractAuthenticatedUser();
if (command.getCodes().isEmpty()) {
List<ErrorResponse> dataValidationErrors = Arrays.asList(new ErrorResponse("validation.msg.organisation.allowed.currencies.cannot.be.blank", "selectedItems"));
throw new NewDataValidationException(dataValidationErrors, "Data validation errors exist.");
}
Set<OrganisationCurrency> allowedCurrencies = new HashSet<OrganisationCurrency>();
for (String currencyCode : command.getCodes()) {
ApplicationCurrency currency = this.applicationCurrencyRepository.findOneByCode(currencyCode);
OrganisationCurrency allowedCurrency = new OrganisationCurrency(
currency.getCode(), currency.getName(),
currency.getDecimalPlaces(), currency.getNameCode(), currency.getDisplaySymbol());
allowedCurrencies.add(allowedCurrency);
}
Organisation org = currentUser.getOrganisation();
org.setAllowedCurrencies(allowedCurrencies);
this.organisationRepository.save(org);
}
private AppUser extractAuthenticatedUser() { private AppUser extractAuthenticatedUser() {
AppUser currentUser = null; AppUser currentUser = null;
SecurityContext context = SecurityContextHolder.getContext(); SecurityContext context = SecurityContextHolder.getContext();
@@ -0,0 +1,51 @@
package org.mifosng.platform.api.configuration;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.mifosng.data.ConfigurationData;
import org.mifosng.data.command.OrganisationCurrencyCommand;
import org.mifosng.platform.configuration.service.ConfigurationReadPlatformService;
import org.mifosng.platform.configuration.service.ConfigurationWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Path("/v1/configurations")
@Component
@Scope("singleton")
public class ConfigurationApiResource {
@Autowired
private ConfigurationReadPlatformService configurationReadPlatformService;
@Autowired
private ConfigurationWritePlatformService configurationWritePlatformService;
@GET
@Path("currency")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON})
public Response retrieveCurrencyDataForConfiguration() {
ConfigurationData configurationData = this.configurationReadPlatformService.retrieveCurrencyConfiguration();
return Response.ok().entity(configurationData).build();
}
@PUT
@Path("currency")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response updateAllowedCurrenciesForOrganisation(OrganisationCurrencyCommand command) {
this.configurationWritePlatformService.updateOrganisationCurrencies(command);
return Response.ok().entity(command).build();
}
}
@@ -2,7 +2,6 @@ package org.mifosng.platform.api.loanproduct;
import java.util.Collection; import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
@@ -10,7 +9,6 @@ import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@@ -74,13 +72,11 @@ public class LoanProductApiResource {
@POST @POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON})
public Response createLoanProduct(@Context HttpServletRequest request) { public Response createLoanProduct(LoanProductCommand command) {
hardcodeUserIntoSecurityContext(); hardcodeUserIntoSecurityContext();
// TODO - FIX mapping to command object on post and also fix error handling of this when it fails. EntityIdentifier entityIdentifier = this.loanProductWritePlatformService.createLoanProduct(command);
EntityIdentifier entityIdentifier = new EntityIdentifier(Long.valueOf(-1));
// this.loanProductWritePlatformService.createLoanProduct(command);
return Response.ok().entity(entityIdentifier).build(); return Response.ok().entity(entityIdentifier).build();
} }
@@ -1,6 +1,9 @@
package org.mifosng.platform.api.office; package org.mifosng.platform.api.office;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import java.util.Locale;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
@@ -12,16 +15,22 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.mifosng.data.ApiParameterError;
import org.mifosng.data.EntityIdentifier; import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.OfficeData; import org.mifosng.data.OfficeData;
import org.mifosng.data.OfficeList; import org.mifosng.data.OfficeList;
import org.mifosng.data.command.OfficeCommand; import org.mifosng.data.command.OfficeCommand;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
import org.mifosng.platform.organisation.service.OfficeReadPlatformService; import org.mifosng.platform.organisation.service.OfficeReadPlatformService;
import org.mifosng.platform.organisation.service.OfficeWritePlatformService; import org.mifosng.platform.organisation.service.OfficeWritePlatformService;
import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUser;
import org.mifosng.platform.user.domain.AppUserRepository; import org.mifosng.platform.user.domain.AppUserRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
@@ -61,12 +70,27 @@ public class OfficeApiResource {
return Response.ok().entity(new OfficeList(offices)).build(); return Response.ok().entity(new OfficeList(offices)).build();
} }
@GET
@Path("template")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({MediaType.APPLICATION_JSON})
public Response retrieveOfficeTemplate() {
hardcodeUserIntoSecurityContext();
OfficeData newOfficeTemplate = this.readPlatformService.retrieveNewOfficeTemplate();
return Response.ok().entity(newOfficeTemplate).build();
}
@POST @POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON})
public Response createOffice(final OfficeCommand command) { public Response createOffice(final OfficeCommand command) {
hardcodeUserIntoSecurityContext(); hardcodeUserIntoSecurityContext();
LocalDate openingDate = parseStringToLocalDate(command.getOpeningDateFormatted(), "openingDateFormatted", command.getDateFormat());
command.setOpeningDate(openingDate);
Long officeId = this.writePlatformService.createOffice(command); Long officeId = this.writePlatformService.createOffice(command);
return Response.ok().entity(new EntityIdentifier(officeId)).build(); return Response.ok().entity(new EntityIdentifier(officeId)).build();
@@ -89,11 +113,33 @@ public class OfficeApiResource {
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON})
public Response updateOffice(@PathParam("officeId") final Long officeId, final OfficeCommand command) { public Response updateOffice(@PathParam("officeId") final Long officeId, final OfficeCommand command) {
LocalDate openingDate = parseStringToLocalDate(command.getOpeningDateFormatted(), "openingDateFormatted", command.getDateFormat());
hardcodeUserIntoSecurityContext(); hardcodeUserIntoSecurityContext();
command.setId(officeId); command.setId(officeId);
command.setOpeningDate(openingDate);
Long entityId = this.writePlatformService.updateOffice(command); Long entityId = this.writePlatformService.updateOffice(command);
return Response.ok().entity(new EntityIdentifier(entityId)).build(); return Response.ok().entity(new EntityIdentifier(entityId)).build();
} }
private LocalDate parseStringToLocalDate(String eventDate, String dateFieldIdentifier, String dateFormat) {
LocalDate eventLocalDate = null;
if (StringUtils.isNotBlank(eventDate)) {
try {
Locale locale = LocaleContextHolder.getLocale();
eventLocalDate = DateTimeFormat.forPattern(dateFormat).withLocale(locale).parseLocalDate(eventDate.toLowerCase(locale));
} catch (IllegalArgumentException e) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.date.format", "The parameter " + dateFieldIdentifier + " is invalid.", dateFieldIdentifier, eventDate);
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
}
return eventLocalDate;
}
} }
@@ -0,0 +1,9 @@
package org.mifosng.platform.configuration.service;
import org.mifosng.data.ConfigurationData;
public interface ConfigurationReadPlatformService {
ConfigurationData retrieveCurrencyConfiguration();
}
@@ -0,0 +1,36 @@
package org.mifosng.platform.configuration.service;
import java.util.ArrayList;
import java.util.List;
import org.mifosng.data.ConfigurationData;
import org.mifosng.data.CurrencyData;
import org.mifosng.platform.currency.service.CurrencyReadPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPlatformService {
private final CurrencyReadPlatformService currencyReadPlatformService;
@Autowired
public ConfigurationReadPlatformServiceImpl(final CurrencyReadPlatformService currencyReadPlatformService) {
this.currencyReadPlatformService = currencyReadPlatformService;
}
@Override
public ConfigurationData retrieveCurrencyConfiguration() {
List<CurrencyData> selectedCurrencyOptions = new ArrayList<CurrencyData>(this.currencyReadPlatformService.retrieveAllowedCurrencies());
List<CurrencyData> currencyOptions = new ArrayList<CurrencyData>(this.currencyReadPlatformService.retrieveAllPlatformCurrencies());
// remove selected currency options
currencyOptions.removeAll(selectedCurrencyOptions);
ConfigurationData configurationData = new ConfigurationData();
configurationData.setCurrencyOptions(currencyOptions);
configurationData.setSelectedCurrencyOptions(selectedCurrencyOptions);
return configurationData;
}
}
@@ -0,0 +1,9 @@
package org.mifosng.platform.configuration.service;
import org.mifosng.data.command.OrganisationCurrencyCommand;
public interface ConfigurationWritePlatformService {
void updateOrganisationCurrencies(OrganisationCurrencyCommand command);
}
@@ -0,0 +1,76 @@
package org.mifosng.platform.configuration.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.mifosng.data.ApiParameterError;
import org.mifosng.data.command.OrganisationCurrencyCommand;
import org.mifosng.platform.currency.domain.ApplicationCurrency;
import org.mifosng.platform.currency.domain.ApplicationCurrencyRepository;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
import org.mifosng.platform.organisation.domain.Organisation;
import org.mifosng.platform.organisation.domain.OrganisationCurrency;
import org.mifosng.platform.organisation.domain.OrganisationRepository;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.mifosng.platform.user.domain.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ConfigurationWritePlatformServiceJpaRepositoryImpl implements ConfigurationWritePlatformService {
private final PlatformSecurityContext context;
private final OrganisationRepository organisationRepository;
private final ApplicationCurrencyRepository applicationCurrencyRepository;
@Autowired
public ConfigurationWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final OrganisationRepository organisationRepository,
final ApplicationCurrencyRepository applicationCurrencyRepository) {
this.context = context;
this.organisationRepository = organisationRepository;
this.applicationCurrencyRepository = applicationCurrencyRepository;
}
@Transactional
@Override
public void updateOrganisationCurrencies(final OrganisationCurrencyCommand command) {
AppUser currentUser = context.authenticatedUser();
if (command.getSelectedItems().isEmpty()) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError("validation.msg.organisation.allowed.currencies.cannot.be.blank", "The parameter selectedItems is invalid.", "selectedItems");
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
Set<OrganisationCurrency> allowedCurrencies = new HashSet<OrganisationCurrency>();
for (String currencyCode : command.getSelectedItems()) {
ApplicationCurrency currency = this.applicationCurrencyRepository.findOneByCode(currencyCode);
if (currency == null) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError("validation.msg.currency.code.invalid", "The parameter selectedItems contains an invalid currency code entry.", "selectedItems", currencyCode);
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
OrganisationCurrency allowedCurrency = new OrganisationCurrency(
currency.getCode(), currency.getName(),
currency.getDecimalPlaces(), currency.getNameCode(), currency.getDisplaySymbol());
allowedCurrencies.add(allowedCurrency);
}
Organisation org = currentUser.getOrganisation();
org.setAllowedCurrencies(allowedCurrencies);
this.organisationRepository.save(org);
}
}
@@ -17,7 +17,7 @@ public class ResponseCorsFilter implements ContainerResponseFilter {
ResponseBuilder resp = Response.fromResponse(response.getResponse()); ResponseBuilder resp = Response.fromResponse(response.getResponse());
resp.header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); resp.header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
String reqHead = request.getHeaderValue("Access-Control-Request-Headers"); String reqHead = request.getHeaderValue("Access-Control-Request-Headers");
@@ -6,7 +6,6 @@ import java.util.List;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.mifosng.data.ApiParameterError; import org.mifosng.data.ApiParameterError;
import org.mifosng.data.command.LoanProductCommand; import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.data.command.LoanProductCommandData;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException; import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
import org.mifosng.platform.loan.domain.AmortizationMethod; import org.mifosng.platform.loan.domain.AmortizationMethod;
import org.mifosng.platform.loan.domain.InterestMethod; import org.mifosng.platform.loan.domain.InterestMethod;
@@ -33,7 +32,7 @@ public class LoanProductCommandValidator {
validateRemainingAttributes(command, dataValidationErrors); validateRemainingAttributes(command, dataValidationErrors);
} }
private void validateRemainingAttributes(LoanProductCommandData command, List<ApiParameterError> dataValidationErrors) { private void validateRemainingAttributes(LoanProductCommand command, List<ApiParameterError> dataValidationErrors) {
if (StringUtils.isBlank(command.getName())) { if (StringUtils.isBlank(command.getName())) {
ApiParameterError error = ApiParameterError.parameterError("validation.msg.product.name.cannot.be.blank", "The parameter name cannot be blank.", "name"); ApiParameterError error = ApiParameterError.parameterError("validation.msg.product.name.cannot.be.blank", "The parameter name cannot be blank.", "name");
@@ -38,7 +38,7 @@ public class Office extends AbstractAuditableCustom<AppUser, Long> {
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id") @JoinColumn(name = "parent_id")
private final Office parent; private Office parent;
@Column(name = "name", nullable = false, length=100) @Column(name = "name", nullable = false, length=100)
private String name; private String name;
@@ -109,6 +109,10 @@ public class Office extends AbstractAuditableCustom<AppUser, Long> {
this.openingDate = newOpeningDate.toDateMidnight().toDate(); this.openingDate = newOpeningDate.toDateMidnight().toDate();
} }
public void update(Office newParent) {
this.parent = newParent;
}
public boolean identifiedBy(String identifier) { public boolean identifiedBy(String identifier) {
return identifier.equalsIgnoreCase(this.name) || identifier.equalsIgnoreCase(this.externalId); return identifier.equalsIgnoreCase(this.name) || identifier.equalsIgnoreCase(this.externalId);
} }
@@ -4,45 +4,39 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.mifosng.data.ApiParameterError; import org.mifosng.data.ApiParameterError;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException; import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
public class OfficeCommandValidator { public class OfficeCommandValidator {
private final String name; private final OfficeCommand command;
private final Long parentId;
private final LocalDate openingDate;
private final String externalId;
public OfficeCommandValidator(String name, Long parentId, LocalDate openingDate, String externalId) { public OfficeCommandValidator(OfficeCommand command) {
this.name = name; this.command = command;
this.parentId = parentId;
this.openingDate = openingDate;
this.externalId = externalId;
} }
public void validate() { public void validate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
if (StringUtils.isBlank(this.name)) { if (StringUtils.isBlank(this.command.getName())) {
ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.name.cannot.be.blank", "The parameter name cannot be blank.", "name"); ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.name.cannot.be.blank", "The parameter name cannot be blank.", "name");
dataValidationErrors.add(error); dataValidationErrors.add(error);
} }
if (this.parentId == null || parentId.intValue() <= 0) { if (!command.isRootOffice() && (this.command.getParentId() == null || this.command.getParentId().intValue() <= 0)) {
ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.parent.cannot.be.blank", "A valid parentId must be provided.", "parentId"); ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.parent.cannot.be.blank", "A valid parentId must be provided.", "parentId");
dataValidationErrors.add(error); dataValidationErrors.add(error);
} }
if (this.openingDate == null) { if (this.command.getOpeningDate() == null) {
ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.opening.date.cannot.be.blank", "The parameter openingDate cannot be blank", "openingDate"); ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.opening.date.cannot.be.blank", "The parameter openingDate cannot be blank", "openingDate");
dataValidationErrors.add(error); dataValidationErrors.add(error);
} }
if (StringUtils.isNotBlank(this.externalId)) { if (StringUtils.isNotBlank(this.command.getExternalId())) {
if (this.externalId.trim().length() > 100) { if (this.command.getExternalId().trim().length() > 100) {
ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.externalId.exceeds.max.length", "The parameter externalId exceeds max length of {0}", "externalId", 100); ApiParameterError error = ApiParameterError.parameterError("validation.msg.office.externalId.exceeds.max.length", "The parameter externalId exceeds max length of {0}", "externalId", 100);
dataValidationErrors.add(error); dataValidationErrors.add(error);
} }
@@ -9,4 +9,6 @@ public interface OfficeReadPlatformService {
Collection<OfficeData> retrieveAllOffices(); Collection<OfficeData> retrieveAllOffices();
OfficeData retrieveOffice(Long officeId); OfficeData retrieveOffice(Long officeId);
OfficeData retrieveNewOfficeTemplate();
} }
@@ -103,4 +103,18 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
throw new PlatformResourceNotFoundException("error.msg.office.id.invalid", "Office with identifier {0} does not exist.", officeId); throw new PlatformResourceNotFoundException("error.msg.office.id.invalid", "Office with identifier {0} does not exist.", officeId);
} }
} }
@Override
public OfficeData retrieveNewOfficeTemplate() {
context.authenticatedUser();
List<OfficeData> allowedParents = new ArrayList<OfficeData>(retrieveAllOffices());
OfficeData officeTemplate = new OfficeData();
officeTemplate.setAllowedParents(allowedParents);
officeTemplate.setOpeningDate(new LocalDate());
return officeTemplate;
}
} }
@@ -17,15 +17,15 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@Service @Service
public class OfficePlatformServiceJpaRepositoryImpl implements OfficeWritePlatformService { public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(OfficePlatformServiceJpaRepositoryImpl.class); private final static Logger logger = LoggerFactory.getLogger(OfficeWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final OfficeRepository officeRepository; private final OfficeRepository officeRepository;
@Autowired @Autowired
public OfficePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final OfficeRepository officeRepository) { public OfficeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final OfficeRepository officeRepository) {
this.context = context; this.context = context;
this.officeRepository = officeRepository; this.officeRepository = officeRepository;
} }
@@ -37,7 +37,7 @@ public class OfficePlatformServiceJpaRepositoryImpl implements OfficeWritePlatfo
try { try {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
OfficeCommandValidator validator = new OfficeCommandValidator(command.getName(), command.getParentId(), command.getOpeningDate(), command.getExternalId()); OfficeCommandValidator validator = new OfficeCommandValidator(command);
validator.validate(); validator.validate();
Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getParentId()); Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getParentId());
@@ -65,13 +65,18 @@ public class OfficePlatformServiceJpaRepositoryImpl implements OfficeWritePlatfo
try { try {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
OfficeCommandValidator validator = new OfficeCommandValidator(command.getName(), command.getParentId(), command.getOpeningDate(), command.getExternalId()); OfficeCommandValidator validator = new OfficeCommandValidator(command);
validator.validate(); validator.validate();
Office office = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getId()); Office office = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getId());
office.update(command.getName(), command.getExternalId(), command.getOpeningDate()); office.update(command.getName(), command.getExternalId(), command.getOpeningDate());
if (!command.isRootOffice()) {
Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, command.getParentId());
office.update(parent);
}
this.officeRepository.save(office); this.officeRepository.save(office);
return office.getId(); return office.getId();
@@ -1,197 +0,0 @@
package org.mifosng.platform.rest;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.mifosng.data.CurrencyData;
import org.mifosng.data.CurrencyList;
import org.mifosng.data.EnumOptionList;
import org.mifosng.data.EnumOptionReadModel;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.ErrorResponseList;
import org.mifosng.data.command.UpdateOrganisationCurrencyCommand;
import org.mifosng.platform.ReadPlatformService;
import org.mifosng.platform.WritePlatformService;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.exceptions.NewDataValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
@Path("/protected/config")
@Component
@Scope("singleton")
public class ApplicationConfigurationResource {
@Autowired
private ReadPlatformService readPlatformService;
@Autowired
private WritePlatformService writePlatformService;
@GET
@Path("currency/allowed")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response retrieveAllowedCurrenciesForOrganisation() {
List<CurrencyData> currencyOptions = this.readPlatformService
.retrieveAllowedCurrencies();
return Response.ok().entity(new CurrencyList(currencyOptions)).build();
}
@PUT
@Path("currency/update")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateAllowedCurrenciesForOrganisation(final UpdateOrganisationCurrencyCommand command) {
try {
this.writePlatformService.updateOrganisationCurrencies(command);
return Response.ok().entity(command).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("currency/all")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveAllPlatformCurrencies() {
try {
List<CurrencyData> currencyOptions = this.readPlatformService
.retrieveAllPlatformCurrencies();
return Response.ok().entity(new CurrencyList(currencyOptions)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("loan/amortization/allowed")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveAllowedLoanAmortizationMethodOptionsForOrganisation() {
try {
List<EnumOptionReadModel> options = this.readPlatformService
.retrieveLoanAmortizationMethodOptions();
return Response.ok().entity(new EnumOptionList(options)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("loan/interestcalculation/allowed")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveAllowedLoanInterestMethodOptionsForOrganisation() {
try {
List<EnumOptionReadModel> options = this.readPlatformService
.retrieveLoanInterestMethodOptions();
return Response.ok().entity(new EnumOptionList(options)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("loan/repaymentfrequency/allowed")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveAllowedRepaymentFrequencyOptionsForOrganisation() {
try {
List<EnumOptionReadModel> options = this.readPlatformService
.retrieveRepaymentFrequencyOptions();
return Response.ok().entity(new EnumOptionList(options)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("loan/interestfrequency/allowed")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveAllowedNominalInterestFrequencyOptionsForOrganisation() {
try {
List<EnumOptionReadModel> options = this.readPlatformService.retrieveInterestFrequencyOptions();
return Response.ok().entity(new EnumOptionList(options)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
}
@@ -1,146 +0,0 @@
package org.mifosng.platform.rest;
import java.util.Arrays;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.ErrorResponseList;
import org.mifosng.data.LoanProductData;
import org.mifosng.data.LoanProductList;
import org.mifosng.data.command.LoanProductCommand;
import org.mifosng.platform.ReadPlatformService;
import org.mifosng.platform.WritePlatformService;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.NewDataValidationException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
@Path("/protected/product/loan")
@Component
@Scope("singleton")
public class LoanProductResource {
@Autowired
private ReadPlatformService readPlatformService;
@Autowired
private WritePlatformService writePlatformService;
@GET
@Path("all")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response retrieveAllLoanProducts() {
Collection<LoanProductData> products = this.readPlatformService
.retrieveAllLoanProducts();
return Response.ok().entity(new LoanProductList(products)).build();
}
@POST
@Path("new")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createLoanProduct(final LoanProductCommand command) {
try {
EntityIdentifier entityIdentifier = this.writePlatformService.createLoanProduct(command);
return Response.ok().entity(entityIdentifier).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@POST
@Path("update")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateLoanProduct(final LoanProductCommand command) {
try {
EntityIdentifier entityIdentifier = this.writePlatformService.updateLoanProduct(command);
return Response.ok().entity(entityIdentifier).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("{productId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveLoanProductDetails(@PathParam("productId") final Long productId) {
try {
LoanProductData loanProduct = this.readPlatformService.retrieveLoanProduct(productId);
return Response.ok().entity(loanProduct).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("empty")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveNewLoanProductDetails() {
try {
LoanProductData loanProduct = this.readPlatformService.retrieveNewLoanProductDetails();
return Response.ok().entity(loanProduct).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
}
@@ -1,135 +0,0 @@
package org.mifosng.platform.rest;
import java.util.Arrays;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.ErrorResponseList;
import org.mifosng.data.OfficeData;
import org.mifosng.data.OfficeList;
import org.mifosng.data.command.OfficeCommand;
import org.mifosng.platform.ReadPlatformService;
import org.mifosng.platform.WritePlatformService;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.exceptions.NewDataValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
@Path("/protected/office")
@Component
@Scope("singleton")
public class OfficeResource {
@Autowired
private ReadPlatformService readPlatformService;
@Autowired
private WritePlatformService writePlatformService;
@GET
@Path("all")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response retrieveOffices() {
try {
Collection<OfficeData> offices = this.readPlatformService.retrieveAllOffices();
return Response.ok().entity(new OfficeList(offices)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@GET
@Path("{officeId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retreiveOffice(@PathParam("officeId") final Long officeId) {
try {
OfficeData office = this.readPlatformService.retrieveOffice(officeId);
return Response.ok().entity(office).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@POST
@Path("new")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createOffice(final OfficeCommand command) {
try {
Long officeId = this.writePlatformService.createOffice(command);
return Response.ok().entity(new EntityIdentifier(officeId)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@POST
@Path("update")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateOffice(final OfficeCommand command) {
try {
Long officeId = this.writePlatformService.updateOffice(command);
return Response.ok().entity(new EntityIdentifier(officeId)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
}