formatting changes for savings related code.

This commit is contained in:
Keith Woodlock
2012-12-04 15:29:11 +00:00
parent d1a1ed60ab
commit 37ae6dae9e
66 changed files with 4414 additions and 4441 deletions
@@ -1,4 +1,4 @@
DROP TABLE IF EXISTS `m_saving_schedule` DROP TABLE IF EXISTS `m_saving_schedule`;
CREATE TABLE `m_saving_schedule` ( CREATE TABLE `m_saving_schedule` (
`id` bigint(20) NOT NULL AUTO_INCREMENT, `id` bigint(20) NOT NULL AUTO_INCREMENT,
`saving_account_id` bigint(20) NOT NULL, `saving_account_id` bigint(20) NOT NULL,
@@ -39,135 +39,136 @@ import org.springframework.stereotype.Component;
@Component @Component
@Scope("singleton") @Scope("singleton")
public class SavingsAccountApiResource { public class SavingsAccountApiResource {
@Autowired
private SavingAccountWritePlatformService savingAccountWritePlatformService;
@Autowired
private SavingAccountReadPlatformService savingAccountReadPlatformService;
@Autowired
private PortfolioApiDataConversionService apiDataConversionService;
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "SAVINGSACCOUNT"; @Autowired
private SavingAccountWritePlatformService savingAccountWritePlatformService;
@Autowired
private PlatformSecurityContext context; @Autowired
private SavingAccountReadPlatformService savingAccountReadPlatformService;
@Autowired
private CalculateSavingSchedule calculateSavingSchedule; @Autowired
private PortfolioApiDataConversionService apiDataConversionService;
private static final Set<String> typicalResponseParameters = new HashSet<String>(
Arrays.asList("id", "status", "externalId", "clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod", "savingsFrequencyType", @Autowired
"totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType", "interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", private PortfolioApiJsonSerializerService apiJsonSerializerService;
"actualCommencementDate", "maturesOnDate", "projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount", "preClosureAllowed",
"preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType")); private final String entityType = "SAVINGSACCOUNT";
@POST @Autowired
@Consumes({MediaType.APPLICATION_JSON}) private PlatformSecurityContext context;
@Produces({MediaType.APPLICATION_JSON})
public String createSavingAccount(@QueryParam("command") final String commandParam, @Autowired
@Context final UriInfo uriInfo,final String jsonRequestBody){ private CalculateSavingSchedule calculateSavingSchedule;
final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(null, jsonRequestBody); private static final Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "status", "externalId",
"clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod",
if (is(commandParam, "calculateSavingSchedule")) { "savingsFrequencyType", "totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType",
"interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", "actualCommencementDate", "maturesOnDate",
"projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount",
"preClosureAllowed", "preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", "isLockinPeriodAllowed",
"lockinPeriod", "lockinPeriodType"));
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String createSavingAccount(@QueryParam("command") final String commandParam, @Context final UriInfo uriInfo,
final String jsonRequestBody) {
final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(null, jsonRequestBody);
if (is(commandParam, "calculateSavingSchedule")) {
CalculateSavingScheduleCommand calculateSavingScheduleCommand = command.toCalculateSavingScheduleCommand(); CalculateSavingScheduleCommand calculateSavingScheduleCommand = command.toCalculateSavingScheduleCommand();
return calculateSavingSchedule(uriInfo,calculateSavingScheduleCommand); return calculateSavingSchedule(uriInfo, calculateSavingScheduleCommand);
} }
EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.createSavingAccount(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(entityIdentifier);
}
private String calculateSavingSchedule(final UriInfo uriInfo, final CalculateSavingScheduleCommand command) {
SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serializeSavingScheduleDataToJson(prettyPrint, responseParameters, savingScheduleData);
}
@PUT EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.createSavingAccount(command);
@Path("{accountId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateSavingAccount(@PathParam("accountId") final Long accountId,final String jsonRequestBody){
final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(accountId, jsonRequestBody);
EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.updateSavingAccount(command);
return Response.ok().entity(entityIdentifier).build();
}
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveAllDepositAccounts(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); return this.apiJsonSerializerService.serializeEntityIdentifier(entityIdentifier);
}
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<SavingAccountData> accounts = this.savingAccountReadPlatformService.retrieveAllSavingsAccounts(); private String calculateSavingSchedule(final UriInfo uriInfo, final CalculateSavingScheduleCommand command) {
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, accounts);
}
@GET
@Path("{accountId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveDepositAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingAccountData account = this.savingAccountReadPlatformService.retrieveSavingsAccount(accountId);
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account);
}
@SuppressWarnings("unused") return this.apiJsonSerializerService.serializeSavingScheduleDataToJson(prettyPrint, responseParameters, savingScheduleData);
@GET }
@Path("template")
@Consumes({MediaType.APPLICATION_JSON}) @PUT
@Produces({MediaType.APPLICATION_JSON}) @Path("{accountId}")
public String retrieveNewDepositAccountDetails( @Consumes({ MediaType.APPLICATION_JSON })
@QueryParam("clientId") final Long clientId, @Produces({ MediaType.APPLICATION_JSON })
@QueryParam("productId") final Long productId, public Response updateSavingAccount(@PathParam("accountId") final Long accountId, final String jsonRequestBody) {
@Context final UriInfo uriInfo) {
final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(accountId, jsonRequestBody);
EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.updateSavingAccount(command);
return Response.ok().entity(entityIdentifier).build();
}
@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveAllDepositAccounts(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<SavingAccountData> accounts = this.savingAccountReadPlatformService.retrieveAllSavingsAccounts();
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, accounts);
}
@GET
@Path("{accountId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveDepositAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingAccountData account = this.savingAccountReadPlatformService.retrieveSavingsAccount(accountId);
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account);
}
@SuppressWarnings("unused")
@GET
@Path("template")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveNewDepositAccountDetails(@QueryParam("clientId") final Long clientId,
@QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingAccountData account = null;
// this.savingAccountReadPlatformService.retrieveNewSavingsAccountDetails(clientId,
// productId);
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account);
}
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingAccountData account = null;
// this.savingAccountReadPlatformService.retrieveNewSavingsAccountDetails(clientId, productId);
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account);
}
private boolean is(final String commandParam, final String commandValue) { private boolean is(final String commandParam, final String commandValue) {
return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue);
} }
@@ -6,58 +6,54 @@ import org.joda.time.LocalDate;
public class CalculateSavingScheduleCommand { public class CalculateSavingScheduleCommand {
private final Long productId; private final Long productId;
private final BigDecimal deposit; private final BigDecimal deposit;
private final Integer payEvery; private final Integer payEvery;
private final Integer paymentFrequencyType; private final Integer paymentFrequencyType;
private final BigDecimal interestRate; private final BigDecimal interestRate;
private final LocalDate paymentsStartingFromDate; private final LocalDate paymentsStartingFromDate;
private final Integer tenure; private final Integer tenure;
public CalculateSavingScheduleCommand(final Long productId,
final BigDecimal deposit,
final Integer payEvery,
final Integer paymentFrequencyType,
final BigDecimal interestRate,
final LocalDate paymentsStartingFromDate,
final Integer tenure) {
this.productId = productId;
this.deposit = deposit;
this.payEvery = payEvery;
this.paymentFrequencyType=paymentFrequencyType;
this.interestRate= interestRate;
this.paymentsStartingFromDate=paymentsStartingFromDate;
this.tenure = tenure;
}
public Long getProductId() { public CalculateSavingScheduleCommand(final Long productId, final BigDecimal deposit, final Integer payEvery,
return this.productId; final Integer paymentFrequencyType, final BigDecimal interestRate, final LocalDate paymentsStartingFromDate,
} final Integer tenure) {
public BigDecimal getDeposit() { this.productId = productId;
return this.deposit; this.deposit = deposit;
} this.payEvery = payEvery;
this.paymentFrequencyType = paymentFrequencyType;
this.interestRate = interestRate;
this.paymentsStartingFromDate = paymentsStartingFromDate;
this.tenure = tenure;
public Integer getPayEvery() { }
return this.payEvery;
}
public Integer getPaymentFrequencyType() { public Long getProductId() {
return this.paymentFrequencyType; return this.productId;
} }
public BigDecimal getInterestRate() { public BigDecimal getDeposit() {
return this.interestRate; return this.deposit;
} }
public LocalDate getPaymentsStartingFromDate() { public Integer getPayEvery() {
return this.paymentsStartingFromDate; return this.payEvery;
} }
public Integer getPaymentFrequencyType() {
return this.paymentFrequencyType;
}
public BigDecimal getInterestRate() {
return this.interestRate;
}
public LocalDate getPaymentsStartingFromDate() {
return this.paymentsStartingFromDate;
}
public Integer getTenure() {
return this.tenure;
}
public Integer getTenure() {
return this.tenure;
}
} }
@@ -6,245 +6,239 @@ import java.util.Set;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
public class SavingAccountCommand { public class SavingAccountCommand {
private final Long id;
private final Long clientId;
private final Long productId;
private final String externalId;
private final String currencyCode; private final Long id;
private final Integer digitsAfterDecimal; private final Long clientId;
private final BigDecimal savingsDepositAmount; private final Long productId;
private final BigDecimal recurringInterestRate; private final String externalId;
private final BigDecimal savingInterestRate;
private final Integer tenure;
private final boolean isLockinPeriodAllowed;
private final Integer lockinPeriod;
private final Integer lockinPeriodType;
private final LocalDate commencementDate;
private final Integer savingProductType;
private final Integer tenureType;
private final Integer frequency;
private final Integer interestType;
private final Integer interestCalculationMethod;
private final BigDecimal minimumBalanceForWithdrawal;
private final boolean isPartialDepositAllowed;
private final Integer payEvery;
private final Set<String> modifiedParameters;
public SavingAccountCommand(final Set<String> modifiedParameters,
final Long id,
final Long clientId,
final Long productId,
final String externalId,final String currencyCode, final Integer digitsAfterDecimal,
final BigDecimal savingsDepositAmount,
final BigDecimal recurringInterestRate, final BigDecimal savingInterestRate,
final Integer tenure, final LocalDate commencementDate,
final Integer savingProductType, final Integer tenureType, final Integer frequency, final Integer interestType,
final BigDecimal minimumBalanceForWithdrawal, final Integer interestCalculationMethod,
final boolean isLockinPeriodAllowed, final boolean isPartialDepositAllowed, final Integer lockInPeriod, final Integer lockinPeriodType,
final Integer payEvery) {
this.id = id;
this.clientId = clientId;
this.productId = productId;
this.externalId = externalId;
this.currencyCode = currencyCode;
this.digitsAfterDecimal = digitsAfterDecimal;
this.savingsDepositAmount = savingsDepositAmount;
this.recurringInterestRate = recurringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure = tenure;
this.modifiedParameters = modifiedParameters;
this.commencementDate = commencementDate;
this.savingProductType=savingProductType;
this.tenureType=tenureType;
this.frequency=frequency;
this.interestType=interestType;
this.isPartialDepositAllowed=isPartialDepositAllowed;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockInPeriod;
this.lockinPeriodType = lockinPeriodType;
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal;
this.interestCalculationMethod=interestCalculationMethod;
this.payEvery = payEvery;
}
public Long getId() { private final String currencyCode;
return id; private final Integer digitsAfterDecimal;
} private final BigDecimal savingsDepositAmount;
private final BigDecimal recurringInterestRate;
private final BigDecimal savingInterestRate;
private final Integer tenure;
public Long getClientId() { private final boolean isLockinPeriodAllowed;
return clientId; private final Integer lockinPeriod;
} private final Integer lockinPeriodType;
public Long getProductId() { private final LocalDate commencementDate;
return productId; private final Integer savingProductType;
} private final Integer tenureType;
private final Integer frequency;
private final Integer interestType;
public String getExternalId() { private final Integer interestCalculationMethod;
return externalId; private final BigDecimal minimumBalanceForWithdrawal;
} private final boolean isPartialDepositAllowed;
private final Integer payEvery;
public String getCurrencyCode() { private final Set<String> modifiedParameters;
return currencyCode;
}
public Integer getDigitsAfterDecimal() { public SavingAccountCommand(final Set<String> modifiedParameters, final Long id, final Long clientId, final Long productId,
return digitsAfterDecimal; final String externalId, final String currencyCode, final Integer digitsAfterDecimal, final BigDecimal savingsDepositAmount,
} final BigDecimal recurringInterestRate, final BigDecimal savingInterestRate, final Integer tenure,
final LocalDate commencementDate, final Integer savingProductType, final Integer tenureType, final Integer frequency,
final Integer interestType, final BigDecimal minimumBalanceForWithdrawal, final Integer interestCalculationMethod,
final boolean isLockinPeriodAllowed, final boolean isPartialDepositAllowed, final Integer lockInPeriod,
final Integer lockinPeriodType, final Integer payEvery) {
this.id = id;
this.clientId = clientId;
this.productId = productId;
this.externalId = externalId;
public BigDecimal getSavingsDepositAmount() { this.currencyCode = currencyCode;
return savingsDepositAmount; this.digitsAfterDecimal = digitsAfterDecimal;
} this.savingsDepositAmount = savingsDepositAmount;
this.recurringInterestRate = recurringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure = tenure;
public BigDecimal getRecurringInterestRate() { this.modifiedParameters = modifiedParameters;
return recurringInterestRate; this.commencementDate = commencementDate;
}
public BigDecimal getSavingInterestRate() { this.savingProductType = savingProductType;
return savingInterestRate; this.tenureType = tenureType;
} this.frequency = frequency;
this.interestType = interestType;
this.isPartialDepositAllowed = isPartialDepositAllowed;
public Integer getTenure() { this.isLockinPeriodAllowed = isLockinPeriodAllowed;
return tenure; this.lockinPeriod = lockInPeriod;
} this.lockinPeriodType = lockinPeriodType;
this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.interestCalculationMethod = interestCalculationMethod;
this.payEvery = payEvery;
}
public boolean isLockinPeriodAllowed() { public Long getId() {
return isLockinPeriodAllowed; return id;
} }
public Integer getLockinPeriod() { public Long getClientId() {
return lockinPeriod; return clientId;
} }
public Integer getLockinPeriodType() { public Long getProductId() {
return lockinPeriodType; return productId;
} }
public LocalDate getCommencementDate() { public String getExternalId() {
return commencementDate; return externalId;
} }
public Integer getSavingProductType() { public String getCurrencyCode() {
return savingProductType; return currencyCode;
} }
public Integer getTenureType() { public Integer getDigitsAfterDecimal() {
return tenureType; return digitsAfterDecimal;
} }
public Integer getFrequency() { public BigDecimal getSavingsDepositAmount() {
return frequency; return savingsDepositAmount;
} }
public Integer getInterestType() { public BigDecimal getRecurringInterestRate() {
return interestType; return recurringInterestRate;
} }
public Integer getInterestCalculationMethod() { public BigDecimal getSavingInterestRate() {
return interestCalculationMethod; return savingInterestRate;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public Integer getTenure() {
return minimumBalanceForWithdrawal; return tenure;
} }
public boolean isPartialDepositAllowed() { public boolean isLockinPeriodAllowed() {
return isPartialDepositAllowed; return isLockinPeriodAllowed;
} }
public Integer getPayEvery() { public Integer getLockinPeriod() {
return this.payEvery; return lockinPeriod;
} }
public boolean isNoFieldChanged() { public Integer getLockinPeriodType() {
return this.modifiedParameters.isEmpty(); return lockinPeriodType;
} }
public boolean isProductIdChanged(){
return this.modifiedParameters.contains("productId");
}
public boolean isExternalIdChanged(){
return this.modifiedParameters.contains("externalId");
}
public boolean isDepositAmountChanged(){
return this.modifiedParameters.contains("deposit");
}
public boolean isTenureInMonthsChanged() { public LocalDate getCommencementDate() {
return this.modifiedParameters.contains("tenureInMonths"); return commencementDate;
} }
public boolean isLockinPeriodChanged() {
return this.modifiedParameters.contains("lockinPeriod");
}
public boolean isPreClosureInterestRateChanged(){
return this.modifiedParameters.contains("preClosureInterestRate");
}
public boolean isPreClosureAllowedChanged() {
return this.modifiedParameters.contains("preClosureAllowed");
}
public boolean isCommencementDateChanged() {
return this.modifiedParameters.contains("commencementDate");
}
public boolean isTenureTypeEnumChanged() { public Integer getSavingProductType() {
return this.modifiedParameters.contains("tenureType"); return savingProductType;
} }
public boolean isSavingProductTypeChanged() { public Integer getTenureType() {
return this.modifiedParameters.contains("savingProductType"); return tenureType;
} }
public boolean isSavingFrequencyTypeChanged() { public Integer getFrequency() {
return this.modifiedParameters.contains("frequency"); return frequency;
} }
public boolean isSavingInterestCalculationMethodChanged() { public Integer getInterestType() {
return this.modifiedParameters.contains("interestCalculationMethod"); return interestType;
} }
public boolean isReccuringInterestRateChanged() { public Integer getInterestCalculationMethod() {
return this.modifiedParameters.contains("recurringInterestRate"); return interestCalculationMethod;
} }
public boolean isSavingInterestRateChanged() { public BigDecimal getMinimumBalanceForWithdrawal() {
return this.modifiedParameters.contains("savingInterestRate"); return minimumBalanceForWithdrawal;
} }
public boolean isLockinPeriodAllowedChanged() { public boolean isPartialDepositAllowed() {
return this.modifiedParameters.contains("isLockinPeriodAllowed"); return isPartialDepositAllowed;
} }
public boolean isLockinPeriodTypeChanged() { public Integer getPayEvery() {
return this.modifiedParameters.contains("lockinPeriodType"); return this.payEvery;
} }
public boolean isPartialDepositAllowedChanged() { public boolean isNoFieldChanged() {
return this.modifiedParameters.contains("isPartialDepositAllowed"); return this.modifiedParameters.isEmpty();
} }
public boolean isPayEveryChanged(){
return this.modifiedParameters.contains("payEvery");
}
public CalculateSavingScheduleCommand toCalculateSavingScheduleCommand() { public boolean isProductIdChanged() {
return new CalculateSavingScheduleCommand(productId, savingsDepositAmount, payEvery, frequency, recurringInterestRate, commencementDate,tenure); return this.modifiedParameters.contains("productId");
} }
public boolean isExternalIdChanged() {
return this.modifiedParameters.contains("externalId");
}
public boolean isDepositAmountChanged() {
return this.modifiedParameters.contains("deposit");
}
public boolean isTenureInMonthsChanged() {
return this.modifiedParameters.contains("tenureInMonths");
}
public boolean isLockinPeriodChanged() {
return this.modifiedParameters.contains("lockinPeriod");
}
public boolean isPreClosureInterestRateChanged() {
return this.modifiedParameters.contains("preClosureInterestRate");
}
public boolean isPreClosureAllowedChanged() {
return this.modifiedParameters.contains("preClosureAllowed");
}
public boolean isCommencementDateChanged() {
return this.modifiedParameters.contains("commencementDate");
}
public boolean isTenureTypeEnumChanged() {
return this.modifiedParameters.contains("tenureType");
}
public boolean isSavingProductTypeChanged() {
return this.modifiedParameters.contains("savingProductType");
}
public boolean isSavingFrequencyTypeChanged() {
return this.modifiedParameters.contains("frequency");
}
public boolean isSavingInterestCalculationMethodChanged() {
return this.modifiedParameters.contains("interestCalculationMethod");
}
public boolean isReccuringInterestRateChanged() {
return this.modifiedParameters.contains("recurringInterestRate");
}
public boolean isSavingInterestRateChanged() {
return this.modifiedParameters.contains("savingInterestRate");
}
public boolean isLockinPeriodAllowedChanged() {
return this.modifiedParameters.contains("isLockinPeriodAllowed");
}
public boolean isLockinPeriodTypeChanged() {
return this.modifiedParameters.contains("lockinPeriodType");
}
public boolean isPartialDepositAllowedChanged() {
return this.modifiedParameters.contains("isPartialDepositAllowed");
}
public boolean isPayEveryChanged() {
return this.modifiedParameters.contains("payEvery");
}
public CalculateSavingScheduleCommand toCalculateSavingScheduleCommand() {
return new CalculateSavingScheduleCommand(productId, savingsDepositAmount, payEvery, frequency, recurringInterestRate,
commencementDate, tenure);
}
} }
@@ -6,29 +6,29 @@ import java.util.Collection;
import org.mifosplatform.organisation.monetary.data.CurrencyData; import org.mifosplatform.organisation.monetary.data.CurrencyData;
public class SavingScheduleData { public class SavingScheduleData {
private final CurrencyData currency;
private final BigDecimal cumulativeDepositDue;
private final Collection<SavingSchedulePeriodData> periods;
public SavingScheduleData(final CurrencyData currency, final BigDecimal cumulativeDepositDue,
final Collection<SavingSchedulePeriodData> periods) {
this.currency = currency;
this.cumulativeDepositDue= cumulativeDepositDue;
this.periods= periods;
}
public CurrencyData getCurrency() { private final CurrencyData currency;
return this.currency; private final BigDecimal cumulativeDepositDue;
} private final Collection<SavingSchedulePeriodData> periods;
public BigDecimal getCumulativeDepositDue() { public SavingScheduleData(final CurrencyData currency, final BigDecimal cumulativeDepositDue,
return this.cumulativeDepositDue; final Collection<SavingSchedulePeriodData> periods) {
} this.currency = currency;
this.cumulativeDepositDue = cumulativeDepositDue;
public Collection<SavingSchedulePeriodData> getPeriods() { this.periods = periods;
return this.periods;
} }
public CurrencyData getCurrency() {
return this.currency;
}
public BigDecimal getCumulativeDepositDue() {
return this.cumulativeDepositDue;
}
public Collection<SavingSchedulePeriodData> getPeriods() {
return this.periods;
}
} }
@@ -5,37 +5,38 @@ import java.math.BigDecimal;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
public class SavingSchedulePeriodData { public class SavingSchedulePeriodData {
private final Integer period;
private final LocalDate dueDate;
private final BigDecimal depositDue;
private final BigDecimal depositPaid;
public SavingSchedulePeriodData(final Integer period, final LocalDate dueDate, final BigDecimal depositDue, final BigDecimal depositPaid) {
this.period = period;
this.dueDate = dueDate;
this.depositDue= depositDue;
this.depositPaid= depositPaid;
}
public static SavingSchedulePeriodData addScheduleInformation(int periodNumber, LocalDate scheduleDate, BigDecimal depositAmountPerPeriod){
return new SavingSchedulePeriodData(periodNumber, scheduleDate, depositAmountPerPeriod, BigDecimal.ZERO);
}
public Integer getPeriod() { private final Integer period;
return this.period; private final LocalDate dueDate;
} private final BigDecimal depositDue;
private final BigDecimal depositPaid;
public LocalDate getDueDate() { public SavingSchedulePeriodData(final Integer period, final LocalDate dueDate, final BigDecimal depositDue, final BigDecimal depositPaid) {
return this.dueDate; this.period = period;
} this.dueDate = dueDate;
this.depositDue = depositDue;
this.depositPaid = depositPaid;
}
public BigDecimal getDepositDue() { public static SavingSchedulePeriodData addScheduleInformation(int periodNumber, LocalDate scheduleDate,
return this.depositDue; BigDecimal depositAmountPerPeriod) {
} return new SavingSchedulePeriodData(periodNumber, scheduleDate, depositAmountPerPeriod, BigDecimal.ZERO);
}
public Integer getPeriod() {
return this.period;
}
public LocalDate getDueDate() {
return this.dueDate;
}
public BigDecimal getDepositDue() {
return this.depositDue;
}
public BigDecimal getDepositPaid() {
return this.depositPaid;
}
public BigDecimal getDepositPaid() {
return this.depositPaid;
}
} }
@@ -6,7 +6,6 @@ import org.joda.time.LocalDate;
import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType;
public interface DepositScheduleDateGenerator { public interface DepositScheduleDateGenerator {
List<LocalDate> generate(LocalDate startDate, Integer paymentPeriods, Integer depositFrequency, PeriodFrequencyType depositFrequencyType);
} List<LocalDate> generate(LocalDate startDate, Integer paymentPeriods, Integer depositFrequency, PeriodFrequencyType depositFrequencyType);
}
@@ -37,345 +37,319 @@ import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum;
import org.mifosplatform.useradministration.domain.AppUser; import org.mifosplatform.useradministration.domain.AppUser;
@Entity @Entity
@Table(name = "m_saving_account", uniqueConstraints = @UniqueConstraint(name="saving_acc_external_id", columnNames = { "external_id" })) @Table(name = "m_saving_account", uniqueConstraints = @UniqueConstraint(name = "saving_acc_external_id", columnNames = { "external_id" }))
public class SavingAccount extends AbstractAuditableCustom<AppUser, Long> { public class SavingAccount extends AbstractAuditableCustom<AppUser, Long> {
@ManyToOne
@JoinColumn(name = "client_id", nullable = false)
private Client client;
@ManyToOne @ManyToOne
@JoinColumn(name = "product_id") @JoinColumn(name = "client_id", nullable = false)
private SavingProduct product; private Client client;
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType;
@Column(name = "savings_product_type", nullable=false)
private SavingProductType savingProductType;
@Column(name = "external_id")
private String externalId;
@SuppressWarnings("unused")
@Embedded
private MonetaryCurrency currency;
@Column(name = "deposit_amount_per_period", scale = 6, precision = 19, nullable = false)
private BigDecimal savingsDepositAmountPerPeriod;
@SuppressWarnings("unused")
@Column(name = "total_deposit_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal totalSavingsAmount;
@Column(name = "reccuring_nominal_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal reccuringInterestRate;
@Column(name = "regular_saving_nominal_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal savingInterestRate;
@Column(name = "tenure", nullable=false)
private Integer tenure;
@Column(name = "tenure_type", nullable=false)
private TenureTypeEnum tenureType;
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType;
@Column(name = "frequency", nullable=false)
private SavingFrequencyType frequency;
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType;
@Column(name = "interest_type", nullable=false)
private SavingsInterestType interestType;
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType;
@Column(name = "interest_calculation_method")
private SavingInterestCalculationMethod interestCalculationMethod;
@Temporal(TemporalType.DATE)
@Column(name = "projected_commencement_date")
private Date projectedCommencementDate;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "actual_commencement_date")
private Date actualCommencementDate;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "matures_on_date")
private Date maturesOnDate;
@SuppressWarnings("unused")
@Column(name = "projected_interest_accrued_on_maturity", scale = 6, precision = 19, nullable = false)
private BigDecimal projectedInterestAccruedOnMaturity;
@SuppressWarnings("unused")
@Column(name = "actual_interest_accrued", scale = 6, precision = 19, nullable = false)
private BigDecimal interestAccrued;
@SuppressWarnings("unused")
@Column(name = "projected_total_maturity_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal projectedTotalOnMaturity;
@SuppressWarnings("unused")
@Column(name = "actual_total_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal total;
@Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal preClosureInterestRate;
@Column(name = "is_preclosure_allowed", nullable = false)
private boolean preClosureAllowed = false;
@Column(name = "is_deleted", nullable=false)
private boolean deleted = false;
@Column(name = "status_enum", nullable = false)
private Integer accountStatus;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "closedon_date")
private Date closedOnDate;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "rejectedon_date")
private Date rejectedOnDate;
@Temporal(TemporalType.DATE)
@Column(name = "withdrawnon_date")
private Date withdrawnOnDate;
@Column(name = "is_lock_in_period_allowed", nullable=false) @ManyToOne
private boolean isLockinPeriodAllowed = false; @JoinColumn(name = "product_id")
private SavingProduct product;
@Column(name = "lock_in_period", nullable=false)
private Integer lockinPeriod;
@Column(name = "lock_in_period_type", nullable=false)
private PeriodFrequencyType lockinPeriodType;
// see
// http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "savingAccount", orphanRemoval = true)
private final List<SavingScheduleInstallments> savingScheduleInstallments = new ArrayList<SavingScheduleInstallments>();
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use
// Integer e.g. private Integer savingProductType;
@Column(name = "savings_product_type", nullable = false)
private SavingProductType savingProductType;
public static SavingAccount openNew( @Column(name = "external_id")
Client client, private String externalId;
SavingProduct product,
String externalId,
Money savingsDeposit,
BigDecimal reccuringInterestRate,
BigDecimal savingInterestRate,
Integer tenure,
LocalDate commencementDate,
TenureTypeEnum tenureTypeEnum,
SavingProductType savingProductType,
SavingFrequencyType savingFrequencyType,
SavingsInterestType interestType,
SavingInterestCalculationMethod savingInterestCalculationMethod,
boolean isLockinPeriodAllowed,
Integer lockinPeriod,
PeriodFrequencyType lockinPeriodType,
ReccuringDepositInterestCalculator reccuringDepositInterestCalculator,
final DepositLifecycleStateMachine lifecycleStateMachine) {
Money futureValueOnMaturity = null;
if(savingProductType.isReccuring()){
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, reccuringInterestRate,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
} else if(savingProductType.isRegular()){
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, savingInterestRate,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
}
return new SavingAccount(client, externalId, product, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure,
commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, interestType, savingInterestCalculationMethod,
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, futureValueOnMaturity, lifecycleStateMachine);
}
public SavingAccount(Client client, String externalId, @SuppressWarnings("unused")
SavingProduct product, Money savingsDeposit, @Embedded
BigDecimal reccuringInterestRate, BigDecimal savingInterestRate, private MonetaryCurrency currency;
Integer tenure, LocalDate commencementDate,
TenureTypeEnum tenureTypeEnum,
SavingProductType savingProductType,
SavingFrequencyType savingFrequencyType, SavingsInterestType interestType,
SavingInterestCalculationMethod savingInterestCalculationMethod,
boolean isLockinPeriodAllowed, Integer lockinPeriod,
PeriodFrequencyType lockinPeriodType, Money futureValueOnMaturity,
final DepositLifecycleStateMachine lifecycleStateMachine) {
DepositAccountStatus from = null;
if (accountStatus != null) {
from = DepositAccountStatus.fromInt(accountStatus);
}
DepositAccountStatus statusEnum = lifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CREATED, from); @Column(name = "deposit_amount_per_period", scale = 6, precision = 19, nullable = false)
accountStatus = statusEnum.getValue(); private BigDecimal savingsDepositAmountPerPeriod;
this.total=BigDecimal.ZERO;
this.preClosureInterestRate=BigDecimal.ZERO;
this.totalSavingsAmount = BigDecimal.ZERO;
this.interestAccrued = BigDecimal.ZERO;
this.client = client;
this.externalId = externalId;
this.product = product;
this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount();
this.currency = savingsDeposit.getCurrency();
this.reccuringInterestRate = reccuringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure =tenure;
this.projectedCommencementDate=commencementDate.toDate();
this.tenureType = tenureTypeEnum;
this.savingProductType = savingProductType;
this.frequency = savingFrequencyType;
this.interestType = interestType;
this.interestCalculationMethod= savingInterestCalculationMethod;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.projectedInterestAccruedOnMaturity =futureValueOnMaturity.getAmount().subtract(BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue()*tenure.doubleValue()));
}
public void modifyAccount(
SavingProduct product,
String externalId,
Money savingsDeposit,
BigDecimal reccuringInterestRate,
BigDecimal savingInterestRate,
Integer tenure,
LocalDate commencementDate,
TenureTypeEnum tenureTypeEnum,
SavingProductType savingProductType,
SavingFrequencyType savingFrequencyType,
SavingInterestCalculationMethod savingInterestCalculationMethod,
boolean isLockinPeriodAllowed,
Integer lockinPeriod,
PeriodFrequencyType lockinPeriodType,
ReccuringDepositInterestCalculator reccuringDepositInterestCalculator) {
Money futureValueOnMaturity = null;
if(savingProductType.isReccuring()){
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, reccuringInterestRate,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
} else if(savingProductType.isRegular()){
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, savingInterestRate,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
}
this.product = product;
this.externalId=externalId;
this.savingsDepositAmountPerPeriod=savingsDeposit.getAmount();
this.reccuringInterestRate=reccuringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure = tenure;
this.projectedCommencementDate = commencementDate.toDate();
this.tenureType = tenureTypeEnum;
this.savingProductType = savingProductType;
this.frequency =savingFrequencyType;
this.interestCalculationMethod = savingInterestCalculationMethod;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
// FIXME - MADHUKAR - futureValueOnMaturity is possibly null
this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.projectedInterestAccruedOnMaturity =futureValueOnMaturity.getAmount().subtract(BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue()*tenure.doubleValue()));
}
public boolean isDeleted() {
return this.deleted;
}
public boolean isPendingApproval() { @SuppressWarnings("unused")
return this.accountStatus.equals(100); @Column(name = "total_deposit_amount", scale = 6, precision = 19, nullable = false)
} private BigDecimal totalSavingsAmount;
public Client getClient() { @Column(name = "reccuring_nominal_interest_rate", scale = 6, precision = 19, nullable = false)
return client; private BigDecimal reccuringInterestRate;
}
public SavingProduct getProduct() { @Column(name = "regular_saving_nominal_interest_rate", scale = 6, precision = 19, nullable = false)
return product; private BigDecimal savingInterestRate;
}
public SavingProductType getSavingProductType() { @Column(name = "tenure", nullable = false)
return savingProductType; private Integer tenure;
}
public String getExternalId() { @Column(name = "tenure_type", nullable = false)
return externalId; private TenureTypeEnum tenureType;
}
public BigDecimal getSavingsDepositAmountPerPeriod() { // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
return savingsDepositAmountPerPeriod; // Integer e.g. private Integer savingProductType;
} @Column(name = "frequency", nullable = false)
private SavingFrequencyType frequency;
public BigDecimal getReccuringInterestRate() { // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
return reccuringInterestRate; // Integer e.g. private Integer savingProductType;
} @Column(name = "interest_type", nullable = false)
private SavingsInterestType interestType;
public BigDecimal getSavingInterestRate() { // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
return savingInterestRate; // Integer e.g. private Integer savingProductType;
} @Column(name = "interest_calculation_method")
private SavingInterestCalculationMethod interestCalculationMethod;
public Integer getTenure() { @Temporal(TemporalType.DATE)
return tenure; @Column(name = "projected_commencement_date")
} private Date projectedCommencementDate;
public TenureTypeEnum getTenureType() { @SuppressWarnings("unused")
return tenureType; @Temporal(TemporalType.DATE)
} @Column(name = "actual_commencement_date")
private Date actualCommencementDate;
public SavingFrequencyType getFrequency() { @SuppressWarnings("unused")
return frequency; @Temporal(TemporalType.DATE)
} @Column(name = "matures_on_date")
private Date maturesOnDate;
public SavingsInterestType getInterestType() { @SuppressWarnings("unused")
return interestType; @Column(name = "projected_interest_accrued_on_maturity", scale = 6, precision = 19, nullable = false)
} private BigDecimal projectedInterestAccruedOnMaturity;
public SavingInterestCalculationMethod getInterestCalculationMethod() { @SuppressWarnings("unused")
return interestCalculationMethod; @Column(name = "actual_interest_accrued", scale = 6, precision = 19, nullable = false)
} private BigDecimal interestAccrued;
public Date getProjectedCommencementDate() { @SuppressWarnings("unused")
return projectedCommencementDate; @Column(name = "projected_total_maturity_amount", scale = 6, precision = 19, nullable = false)
} private BigDecimal projectedTotalOnMaturity;
public BigDecimal getPreClosureInterestRate() { @SuppressWarnings("unused")
return preClosureInterestRate; @Column(name = "actual_total_amount", scale = 6, precision = 19, nullable = false)
} private BigDecimal total;
public boolean isPreClosureAllowed() { @Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false)
return preClosureAllowed; private BigDecimal preClosureInterestRate;
}
public Date getWithdrawnOnDate() { @Column(name = "is_preclosure_allowed", nullable = false)
return withdrawnOnDate; private boolean preClosureAllowed = false;
}
public boolean isLockinPeriodAllowed() { @Column(name = "is_deleted", nullable = false)
return isLockinPeriodAllowed; private boolean deleted = false;
}
public Integer getLockinPeriod() { @Column(name = "status_enum", nullable = false)
return lockinPeriod; private Integer accountStatus;
}
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "closedon_date")
private Date closedOnDate;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "rejectedon_date")
private Date rejectedOnDate;
@Temporal(TemporalType.DATE)
@Column(name = "withdrawnon_date")
private Date withdrawnOnDate;
@Column(name = "is_lock_in_period_allowed", nullable = false)
private boolean isLockinPeriodAllowed = false;
@Column(name = "lock_in_period", nullable = false)
private Integer lockinPeriod;
@Column(name = "lock_in_period_type", nullable = false)
private PeriodFrequencyType lockinPeriodType;
// see
// http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "savingAccount", orphanRemoval = true)
private final List<SavingScheduleInstallments> savingScheduleInstallments = new ArrayList<SavingScheduleInstallments>();
public static SavingAccount openNew(Client client, SavingProduct product, String externalId, Money savingsDeposit,
BigDecimal reccuringInterestRate, BigDecimal savingInterestRate, Integer tenure, LocalDate commencementDate,
TenureTypeEnum tenureTypeEnum, SavingProductType savingProductType, SavingFrequencyType savingFrequencyType,
SavingsInterestType interestType, SavingInterestCalculationMethod savingInterestCalculationMethod,
boolean isLockinPeriodAllowed, Integer lockinPeriod, PeriodFrequencyType lockinPeriodType,
ReccuringDepositInterestCalculator reccuringDepositInterestCalculator, final DepositLifecycleStateMachine lifecycleStateMachine) {
Money futureValueOnMaturity = null;
if (savingProductType.isReccuring()) {
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
reccuringInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
} else if (savingProductType.isRegular()) {
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
savingInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
}
return new SavingAccount(client, externalId, product, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure,
commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, interestType, savingInterestCalculationMethod,
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, futureValueOnMaturity, lifecycleStateMachine);
}
public SavingAccount(Client client, String externalId, SavingProduct product, Money savingsDeposit, BigDecimal reccuringInterestRate,
BigDecimal savingInterestRate, Integer tenure, LocalDate commencementDate, TenureTypeEnum tenureTypeEnum,
SavingProductType savingProductType, SavingFrequencyType savingFrequencyType, SavingsInterestType interestType,
SavingInterestCalculationMethod savingInterestCalculationMethod, boolean isLockinPeriodAllowed, Integer lockinPeriod,
PeriodFrequencyType lockinPeriodType, Money futureValueOnMaturity, final DepositLifecycleStateMachine lifecycleStateMachine) {
DepositAccountStatus from = null;
if (accountStatus != null) {
from = DepositAccountStatus.fromInt(accountStatus);
}
DepositAccountStatus statusEnum = lifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CREATED, from);
accountStatus = statusEnum.getValue();
this.total = BigDecimal.ZERO;
this.preClosureInterestRate = BigDecimal.ZERO;
this.totalSavingsAmount = BigDecimal.ZERO;
this.interestAccrued = BigDecimal.ZERO;
this.client = client;
this.externalId = externalId;
this.product = product;
this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount();
this.currency = savingsDeposit.getCurrency();
this.reccuringInterestRate = reccuringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure = tenure;
this.projectedCommencementDate = commencementDate.toDate();
this.tenureType = tenureTypeEnum;
this.savingProductType = savingProductType;
this.frequency = savingFrequencyType;
this.interestType = interestType;
this.interestCalculationMethod = savingInterestCalculationMethod;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.projectedInterestAccruedOnMaturity = futureValueOnMaturity.getAmount().subtract(
BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue() * tenure.doubleValue()));
}
public void modifyAccount(SavingProduct product, String externalId, Money savingsDeposit, BigDecimal reccuringInterestRate,
BigDecimal savingInterestRate, Integer tenure, LocalDate commencementDate, TenureTypeEnum tenureTypeEnum,
SavingProductType savingProductType, SavingFrequencyType savingFrequencyType,
SavingInterestCalculationMethod savingInterestCalculationMethod, boolean isLockinPeriodAllowed, Integer lockinPeriod,
PeriodFrequencyType lockinPeriodType, ReccuringDepositInterestCalculator reccuringDepositInterestCalculator) {
Money futureValueOnMaturity = null;
if (savingProductType.isReccuring()) {
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
reccuringInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
} else if (savingProductType.isRegular()) {
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
savingInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
}
this.product = product;
this.externalId = externalId;
this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount();
this.reccuringInterestRate = reccuringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure = tenure;
this.projectedCommencementDate = commencementDate.toDate();
this.tenureType = tenureTypeEnum;
this.savingProductType = savingProductType;
this.frequency = savingFrequencyType;
this.interestCalculationMethod = savingInterestCalculationMethod;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
// FIXME - MADHUKAR - futureValueOnMaturity is possibly null
this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.projectedInterestAccruedOnMaturity = futureValueOnMaturity.getAmount().subtract(
BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue() * tenure.doubleValue()));
}
public boolean isDeleted() {
return this.deleted;
}
public boolean isPendingApproval() {
return this.accountStatus.equals(100);
}
public Client getClient() {
return client;
}
public SavingProduct getProduct() {
return product;
}
public SavingProductType getSavingProductType() {
return savingProductType;
}
public String getExternalId() {
return externalId;
}
public BigDecimal getSavingsDepositAmountPerPeriod() {
return savingsDepositAmountPerPeriod;
}
public BigDecimal getReccuringInterestRate() {
return reccuringInterestRate;
}
public BigDecimal getSavingInterestRate() {
return savingInterestRate;
}
public Integer getTenure() {
return tenure;
}
public TenureTypeEnum getTenureType() {
return tenureType;
}
public SavingFrequencyType getFrequency() {
return frequency;
}
public SavingsInterestType getInterestType() {
return interestType;
}
public SavingInterestCalculationMethod getInterestCalculationMethod() {
return interestCalculationMethod;
}
public Date getProjectedCommencementDate() {
return projectedCommencementDate;
}
public BigDecimal getPreClosureInterestRate() {
return preClosureInterestRate;
}
public boolean isPreClosureAllowed() {
return preClosureAllowed;
}
public Date getWithdrawnOnDate() {
return withdrawnOnDate;
}
public boolean isLockinPeriodAllowed() {
return isLockinPeriodAllowed;
}
public Integer getLockinPeriod() {
return lockinPeriod;
}
public PeriodFrequencyType getLockinPeriodType() {
return lockinPeriodType;
}
public void addSavingScheduleInstallment(final SavingScheduleInstallments installment) {
installment.updateAccount(this);
this.savingScheduleInstallments.add(installment);
}
public PeriodFrequencyType getLockinPeriodType() {
return lockinPeriodType;
}
public void addSavingScheduleInstallment(final SavingScheduleInstallments installment) {
installment.updateAccount(this);
this.savingScheduleInstallments.add(installment);
}
} }
@@ -3,8 +3,6 @@ package org.mifosplatform.portfolio.savingsaccount.domain;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface SavingAccountRepository extends public interface SavingAccountRepository extends JpaRepository<SavingAccount, Long>, JpaSpecificationExecutor<SavingAccount> {
JpaRepository<SavingAccount, Long>,
JpaSpecificationExecutor<SavingAccount>{
} }
@@ -15,46 +15,45 @@ import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom;
import org.mifosplatform.useradministration.domain.AppUser; import org.mifosplatform.useradministration.domain.AppUser;
@Entity @Entity
@Table(name="m_saving_schedule") @Table(name = "m_saving_schedule")
public class SavingScheduleInstallments extends AbstractAuditableCustom<AppUser, Long> { public class SavingScheduleInstallments extends AbstractAuditableCustom<AppUser, Long> {
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "saving_account_id", nullable=false) @JoinColumn(name = "saving_account_id", nullable = false)
private SavingAccount savingAccount; private SavingAccount savingAccount;
@Temporal(TemporalType.DATE) @Temporal(TemporalType.DATE)
@Column(name = "duedate", nullable=false) @Column(name = "duedate", nullable = false)
private final Date dueDate; private final Date dueDate;
@Column(name = "installment", nullable=false) @Column(name = "installment", nullable = false)
private final Integer installmentNumber; private final Integer installmentNumber;
@Column(name = "deposit", scale=6, precision=19, nullable=false) @Column(name = "deposit", scale = 6, precision = 19, nullable = false)
private BigDecimal deposit; private BigDecimal deposit;
@Temporal(TemporalType.DATE) @Temporal(TemporalType.DATE)
@Column(name = "payment_date", nullable=true) @Column(name = "payment_date", nullable = true)
private final Date paymentDate; private final Date paymentDate;
@Column(name = "deposit_paid", scale=6, precision=19, nullable=true) @Column(name = "deposit_paid", scale = 6, precision = 19, nullable = true)
private BigDecimal depositPaid; private BigDecimal depositPaid;
@Column(name="completed_derived", nullable=false) @Column(name = "completed_derived", nullable = false)
private boolean completed; private boolean completed;
public SavingScheduleInstallments(SavingAccount account, Date dueDate, public SavingScheduleInstallments(SavingAccount account, Date dueDate, Integer installmentNumber, BigDecimal deposit) {
Integer installmentNumber, BigDecimal deposit) { this.savingAccount = account;
this.savingAccount = account; this.dueDate = dueDate;
this.dueDate = dueDate; this.installmentNumber = installmentNumber;
this.installmentNumber = installmentNumber; this.deposit = deposit;
this.deposit = deposit; this.paymentDate = null;
this.paymentDate = null; this.depositPaid = BigDecimal.ZERO;
this.depositPaid = BigDecimal.ZERO; this.completed = false;
this.completed = false; }
}
public void updateAccount(SavingAccount account) {
public void updateAccount(SavingAccount account){ this.savingAccount = account;
this.savingAccount = account; }
}
} }
@@ -4,8 +4,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN
public class SavingAccountNotFoundException extends AbstractPlatformResourceNotFoundException { public class SavingAccountNotFoundException extends AbstractPlatformResourceNotFoundException {
public SavingAccountNotFoundException(final Long id) { public SavingAccountNotFoundException(final Long id) {
super("error.msg.saving.account.id.invalid", "Saving account with identifier " + id + " does not exist", id); super("error.msg.saving.account.id.invalid", "Saving account with identifier " + id + " does not exist", id);
} }
}
}
@@ -4,7 +4,6 @@ import org.mifosplatform.portfolio.savingsaccount.command.CalculateSavingSchedul
import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData;
public interface CalculateSavingSchedule { public interface CalculateSavingSchedule {
SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command);
} SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command);
}
@@ -17,46 +17,44 @@ import org.springframework.stereotype.Service;
@Service @Service
public class CalculateSavingScheduleImpl implements CalculateSavingSchedule { public class CalculateSavingScheduleImpl implements CalculateSavingSchedule {
private final PlatformSecurityContext context;
private final SavingProductRepository savingProductRepository;
private final SavingScheduleGenerator savingScheduleGenerator;
private final ApplicationCurrencyRepository applicationCurrencyRepository;
@Autowired
public CalculateSavingScheduleImpl(
final PlatformSecurityContext context,
final SavingProductRepository savingProductRepository,
final ApplicationCurrencyRepository applicationCurrencyRepository) {
this.context = context;
this.savingProductRepository = savingProductRepository;
this.savingScheduleGenerator = new SavingScheduleGenerator();
this.applicationCurrencyRepository = applicationCurrencyRepository;
}
@Override private final PlatformSecurityContext context;
public SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command) { private final SavingProductRepository savingProductRepository;
private final SavingScheduleGenerator savingScheduleGenerator;
context.authenticatedUser(); private final ApplicationCurrencyRepository applicationCurrencyRepository;
// FIXME Validations should write here @Autowired
final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId()); public CalculateSavingScheduleImpl(final PlatformSecurityContext context, final SavingProductRepository savingProductRepository,
if (savingProduct == null) final ApplicationCurrencyRepository applicationCurrencyRepository) {
throw new SavingProductNotFoundException(command.getProductId()); this.context = context;
this.savingProductRepository = savingProductRepository;
final Integer depositFrequency = command.getPayEvery(); this.savingScheduleGenerator = new SavingScheduleGenerator();
final PeriodFrequencyType depositFrequencyType = PeriodFrequencyType.fromInt(command.getPaymentFrequencyType()); this.applicationCurrencyRepository = applicationCurrencyRepository;
final LocalDate scheduleStartDate = command.getPaymentsStartingFromDate(); }
@SuppressWarnings("unused")
final BigDecimal interestRate = command.getInterestRate(); @Override
final BigDecimal depositAmountPerPeriod = command.getDeposit(); public SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command) {
final Integer tenure = command.getTenure();
final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneByCode(savingProduct.getCurrency().getCode()); context.authenticatedUser();
SavingScheduleData savingScheduleData = savingScheduleGenerator.generate(scheduleStartDate,depositAmountPerPeriod, // FIXME Validations should write here
depositFrequency,depositFrequencyType,savingProduct,tenure,applicationCurrency); final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId());
if (savingProduct == null) throw new SavingProductNotFoundException(command.getProductId());
return savingScheduleData;
} final Integer depositFrequency = command.getPayEvery();
final PeriodFrequencyType depositFrequencyType = PeriodFrequencyType.fromInt(command.getPaymentFrequencyType());
final LocalDate scheduleStartDate = command.getPaymentsStartingFromDate();
@SuppressWarnings("unused")
final BigDecimal interestRate = command.getInterestRate();
final BigDecimal depositAmountPerPeriod = command.getDeposit();
final Integer tenure = command.getTenure();
final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneByCode(savingProduct.getCurrency()
.getCode());
SavingScheduleData savingScheduleData = savingScheduleGenerator.generate(scheduleStartDate, depositAmountPerPeriod,
depositFrequency, depositFrequencyType, savingProduct, tenure, applicationCurrency);
return savingScheduleData;
}
} }
@@ -7,41 +7,42 @@ import org.joda.time.LocalDate;
import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType;
import org.mifosplatform.portfolio.savingsaccount.domain.DepositScheduleDateGenerator; import org.mifosplatform.portfolio.savingsaccount.domain.DepositScheduleDateGenerator;
public class DefaultDepositScheduleDateGenerator implements DepositScheduleDateGenerator { public class DefaultDepositScheduleDateGenerator implements DepositScheduleDateGenerator {
@Override @Override
public List<LocalDate> generate(LocalDate scheuleStartDate, Integer paymentPeriods, Integer depositFrequency, PeriodFrequencyType depositFrequencyType) { public List<LocalDate> generate(LocalDate scheuleStartDate, Integer paymentPeriods, Integer depositFrequency,
PeriodFrequencyType depositFrequencyType) {
List<LocalDate> duePaymentPeriodDates = new ArrayList<LocalDate>(depositFrequency);
LocalDate startDate = scheuleStartDate; List<LocalDate> duePaymentPeriodDates = new ArrayList<LocalDate>(depositFrequency);
LocalDate startDate = scheuleStartDate;
for (int period=1; period <= paymentPeriods; period++){
for (int period = 1; period <= paymentPeriods; period++) {
LocalDate duePaymentPeriodDate = startDate;
if (period == 1) { LocalDate duePaymentPeriodDate = startDate;
duePaymentPeriodDate = startDate; if (period == 1) {
} else { duePaymentPeriodDate = startDate;
switch (depositFrequencyType) { } else {
case DAYS: switch (depositFrequencyType) {
duePaymentPeriodDate = startDate.plusDays(depositFrequency); case DAYS:
break; duePaymentPeriodDate = startDate.plusDays(depositFrequency);
case WEEKS: break;
duePaymentPeriodDate = startDate.plusWeeks(depositFrequency); case WEEKS:
break; duePaymentPeriodDate = startDate.plusWeeks(depositFrequency);
case MONTHS: break;
duePaymentPeriodDate = startDate.plusMonths(depositFrequency); case MONTHS:
break; duePaymentPeriodDate = startDate.plusMonths(depositFrequency);
case YEARS: break;
duePaymentPeriodDate = startDate.plusYears(depositFrequency); case YEARS:
break; duePaymentPeriodDate = startDate.plusYears(depositFrequency);
case INVALID: break;
break; case INVALID:
} break;
} }
duePaymentPeriodDates.add(duePaymentPeriodDate); }
startDate = duePaymentPeriodDate; duePaymentPeriodDates.add(duePaymentPeriodDate);
} startDate = duePaymentPeriodDate;
}
return duePaymentPeriodDates;
} return duePaymentPeriodDates;
}
} }
@@ -33,191 +33,186 @@ import org.springframework.stereotype.Service;
@Service @Service
public class SavingAccountAssembler { public class SavingAccountAssembler {
private final ClientRepository clientRepository;
private final SavingProductRepository savingProductRepository;
private final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator;
private final CalculateSavingSchedule calculateSavingSchedule;
@Autowired
public SavingAccountAssembler(final ClientRepository clientRepository,final SavingProductRepository savingProductRepository,
final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator,final CalculateSavingSchedule calculateSavingSchedule) {
this.clientRepository=clientRepository;
this.savingProductRepository=savingProductRepository;
this.reccuringDepositInterestCalculator=reccuringDepositInterestCalculator;
this.calculateSavingSchedule = calculateSavingSchedule;
}
//minimumBalanceForWithdrawal,isPartialDepositAllowed
public SavingAccount assembleFrom(SavingAccountCommand command){
Client client = this.clientRepository.findOne(command.getClientId());
if (client == null || client.isDeleted()) {
throw new ClientNotFoundException(command.getClientId());
}
SavingProduct product=this.savingProductRepository.findOne(command.getProductId());
if(product == null || product.isDeleted()){
throw new SavingProductNotFoundException(command.getProductId());
}
MonetaryCurrency currency = product.getCurrency();
if(command.getCurrencyCode() != null && command.getDigitsAfterDecimal() != null){
currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
}
Money savingsDeposit = Money.of(currency, command.getSavingsDepositAmount());
Integer tenure = product.getSavingProductRelatedDetail().getTenure();
if(command.getTenure() != null){
tenure=command.getTenure();
}
TenureTypeEnum tenureTypeEnum=product.getSavingProductRelatedDetail().getTenureType();
if (command.getTenureType() != null) {
tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType());
}
SavingProductType savingProductType= product.getSavingProductRelatedDetail().getSavingProductType();
if(command.getSavingProductType() != null){
savingProductType = SavingProductType.fromInt(command.getSavingProductType());
}
SavingFrequencyType savingFrequencyType = product.getSavingProductRelatedDetail().getFrequency();
if (command.getFrequency() != null) {
savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
}
SavingInterestCalculationMethod savingInterestCalculationMethod = product.getSavingProductRelatedDetail().getInterestCalculationMethod();
if (command.getInterestCalculationMethod() != null) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
}
SavingsInterestType interestType = product.getSavingProductRelatedDetail().getInterestType();
if (command.getInterestType() != null) {
interestType = SavingsInterestType.fromInt(command.getInterestType());
}
BigDecimal reccuringInterestRate = command.getRecurringInterestRate();
BigDecimal savingInterestRate = product.getInterestRate();
if(command.getSavingInterestRate() != null)
savingInterestRate = command.getSavingInterestRate();
boolean isLockinPeriodAllowed = product.getSavingProductRelatedDetail().isLockinPeriodAllowed();
if(command.isLockinPeriodChanged()){
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = product.getSavingProductRelatedDetail().getLockinPeriod();
if(command.getLockinPeriod() != null){
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = product.getSavingProductRelatedDetail().getLockinPeriodType();
if(command.getLockinPeriodType() != null){
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
SavingAccount account = SavingAccount.openNew(client, product, command.getExternalId(),savingsDeposit,
reccuringInterestRate,savingInterestRate,tenure,command.getCommencementDate(),tenureTypeEnum, savingProductType,
savingFrequencyType, interestType, savingInterestCalculationMethod, isLockinPeriodAllowed,lockinPeriod, lockinPeriodType,
this.reccuringDepositInterestCalculator, defaultDepositLifecycleStateMachine());
SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command.toCalculateSavingScheduleCommand());
for(SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()){
final SavingScheduleInstallments installment = new SavingScheduleInstallments(
account,
savingSchedulePeriodData.getDueDate().toDate(),
savingSchedulePeriodData.getPeriod(),
savingSchedulePeriodData.getDepositDue());
account.addSavingScheduleInstallment(installment);
}
return account;
}
public void assembleFrom(SavingAccountCommand command, SavingAccount account) { private final ClientRepository clientRepository;
private final SavingProductRepository savingProductRepository;
SavingProduct product=account.getProduct(); private final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator;
if(command.isProductIdChanged()){ private final CalculateSavingSchedule calculateSavingSchedule;
if(product.getId() != command.getProductId()){
product = this.savingProductRepository.findOne(command.getProductId()); @Autowired
if(product == null || product.isDeleted()) public SavingAccountAssembler(final ClientRepository clientRepository, final SavingProductRepository savingProductRepository,
throw new SavingProductNotFoundException(command.getProductId()); final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator,
} final CalculateSavingSchedule calculateSavingSchedule) {
} this.clientRepository = clientRepository;
this.savingProductRepository = savingProductRepository;
String externalId = account.getExternalId(); this.reccuringDepositInterestCalculator = reccuringDepositInterestCalculator;
if(command.isExternalIdChanged()){ this.calculateSavingSchedule = calculateSavingSchedule;
externalId = command.getExternalId(); }
}
// minimumBalanceForWithdrawal,isPartialDepositAllowed
Money savingsDeposit = Money.of(product.getCurrency(), account.getSavingsDepositAmountPerPeriod()); public SavingAccount assembleFrom(SavingAccountCommand command) {
if(command.isDepositAmountChanged()){
savingsDeposit = Money.of(product.getCurrency(), command.getSavingsDepositAmount()); Client client = this.clientRepository.findOne(command.getClientId());
} if (client == null || client.isDeleted()) { throw new ClientNotFoundException(command.getClientId()); }
Integer tenure = account.getTenure();
if(command.isTenureInMonthsChanged()){ SavingProduct product = this.savingProductRepository.findOne(command.getProductId());
tenure = command.getTenure(); if (product == null || product.isDeleted()) { throw new SavingProductNotFoundException(command.getProductId()); }
}
MonetaryCurrency currency = product.getCurrency();
LocalDate commencementDate = new LocalDate(account.getProjectedCommencementDate()); if (command.getCurrencyCode() != null && command.getDigitsAfterDecimal() != null) {
if (command.isCommencementDateChanged()) { currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
commencementDate = command.getCommencementDate(); }
}
Money savingsDeposit = Money.of(currency, command.getSavingsDepositAmount());
TenureTypeEnum tenureTypeEnum=account.getTenureType();
if(command.isTenureTypeEnumChanged()){ Integer tenure = product.getSavingProductRelatedDetail().getTenure();
tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType()); if (command.getTenure() != null) {
} tenure = command.getTenure();
}
SavingProductType savingProductType= account.getSavingProductType();
if (command.isSavingProductTypeChanged()) { TenureTypeEnum tenureTypeEnum = product.getSavingProductRelatedDetail().getTenureType();
savingProductType = SavingProductType.fromInt(command.getSavingProductType()); if (command.getTenureType() != null) {
} tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType());
}
SavingFrequencyType savingFrequencyType = account.getFrequency();
if (command.isSavingFrequencyTypeChanged()) { SavingProductType savingProductType = product.getSavingProductRelatedDetail().getSavingProductType();
savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency()); if (command.getSavingProductType() != null) {
} savingProductType = SavingProductType.fromInt(command.getSavingProductType());
}
SavingInterestCalculationMethod savingInterestCalculationMethod =account.getInterestCalculationMethod();
if (command.isSavingInterestCalculationMethodChanged()) { SavingFrequencyType savingFrequencyType = product.getSavingProductRelatedDetail().getFrequency();
savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod()); if (command.getFrequency() != null) {
} savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
}
BigDecimal reccuringInterestRate = account.getReccuringInterestRate();
if (command.isReccuringInterestRateChanged()) { SavingInterestCalculationMethod savingInterestCalculationMethod = product.getSavingProductRelatedDetail()
reccuringInterestRate = command.getRecurringInterestRate(); .getInterestCalculationMethod();
} if (command.getInterestCalculationMethod() != null) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
BigDecimal savingInterestRate = account.getSavingInterestRate(); }
if (command.isSavingInterestRateChanged()) {
savingInterestRate = command.getSavingInterestRate(); SavingsInterestType interestType = product.getSavingProductRelatedDetail().getInterestType();
} if (command.getInterestType() != null) {
interestType = SavingsInterestType.fromInt(command.getInterestType());
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); }
if (command.isLockinPeriodAllowedChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed(); BigDecimal reccuringInterestRate = command.getRecurringInterestRate();
} BigDecimal savingInterestRate = product.getInterestRate();
if (command.getSavingInterestRate() != null) savingInterestRate = command.getSavingInterestRate();
Integer lockinPeriod =account.getLockinPeriod();
if (command.isLockinPeriodChanged()) { boolean isLockinPeriodAllowed = product.getSavingProductRelatedDetail().isLockinPeriodAllowed();
lockinPeriod = command.getLockinPeriod(); if (command.isLockinPeriodChanged()) {
} isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
if (command.isLockinPeriodTypeChanged()) { Integer lockinPeriod = product.getSavingProductRelatedDetail().getLockinPeriod();
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); if (command.getLockinPeriod() != null) {
} lockinPeriod = command.getLockinPeriod();
account.modifyAccount(product, externalId, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure, }
commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, savingInterestCalculationMethod,
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, this.reccuringDepositInterestCalculator); PeriodFrequencyType lockinPeriodType = product.getSavingProductRelatedDetail().getLockinPeriodType();
if (command.getLockinPeriodType() != null) {
} lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() {
List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values()); SavingAccount account = SavingAccount.openNew(client, product, command.getExternalId(), savingsDeposit, reccuringInterestRate,
return new DepositLifecycleStateMachineImpl(allowedDepositStatuses); savingInterestRate, tenure, command.getCommencementDate(), tenureTypeEnum, savingProductType, savingFrequencyType,
} interestType, savingInterestCalculationMethod, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType,
this.reccuringDepositInterestCalculator, defaultDepositLifecycleStateMachine());
SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command
.toCalculateSavingScheduleCommand());
for (SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()) {
final SavingScheduleInstallments installment = new SavingScheduleInstallments(account, savingSchedulePeriodData.getDueDate()
.toDate(), savingSchedulePeriodData.getPeriod(), savingSchedulePeriodData.getDepositDue());
account.addSavingScheduleInstallment(installment);
}
return account;
}
public void assembleFrom(SavingAccountCommand command, SavingAccount account) {
SavingProduct product = account.getProduct();
if (command.isProductIdChanged()) {
if (product.getId() != command.getProductId()) {
product = this.savingProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) throw new SavingProductNotFoundException(command.getProductId());
}
}
String externalId = account.getExternalId();
if (command.isExternalIdChanged()) {
externalId = command.getExternalId();
}
Money savingsDeposit = Money.of(product.getCurrency(), account.getSavingsDepositAmountPerPeriod());
if (command.isDepositAmountChanged()) {
savingsDeposit = Money.of(product.getCurrency(), command.getSavingsDepositAmount());
}
Integer tenure = account.getTenure();
if (command.isTenureInMonthsChanged()) {
tenure = command.getTenure();
}
LocalDate commencementDate = new LocalDate(account.getProjectedCommencementDate());
if (command.isCommencementDateChanged()) {
commencementDate = command.getCommencementDate();
}
TenureTypeEnum tenureTypeEnum = account.getTenureType();
if (command.isTenureTypeEnumChanged()) {
tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType());
}
SavingProductType savingProductType = account.getSavingProductType();
if (command.isSavingProductTypeChanged()) {
savingProductType = SavingProductType.fromInt(command.getSavingProductType());
}
SavingFrequencyType savingFrequencyType = account.getFrequency();
if (command.isSavingFrequencyTypeChanged()) {
savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
}
SavingInterestCalculationMethod savingInterestCalculationMethod = account.getInterestCalculationMethod();
if (command.isSavingInterestCalculationMethodChanged()) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
}
BigDecimal reccuringInterestRate = account.getReccuringInterestRate();
if (command.isReccuringInterestRateChanged()) {
reccuringInterestRate = command.getRecurringInterestRate();
}
BigDecimal savingInterestRate = account.getSavingInterestRate();
if (command.isSavingInterestRateChanged()) {
savingInterestRate = command.getSavingInterestRate();
}
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
if (command.isLockinPeriodAllowedChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = account.getLockinPeriod();
if (command.isLockinPeriodChanged()) {
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
if (command.isLockinPeriodTypeChanged()) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
account.modifyAccount(product, externalId, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure, commencementDate,
tenureTypeEnum, savingProductType, savingFrequencyType, savingInterestCalculationMethod, isLockinPeriodAllowed,
lockinPeriod, lockinPeriodType, this.reccuringDepositInterestCalculator);
}
private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() {
List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values());
return new DepositLifecycleStateMachineImpl(allowedDepositStatuses);
}
} }
@@ -14,31 +14,27 @@ import org.springframework.stereotype.Service;
@Service @Service
public class SavingProductRelatedDetailAssembler { public class SavingProductRelatedDetailAssembler {
private final SavingProductRepository savingProductRepository;
@Autowired
public SavingProductRelatedDetailAssembler(final SavingProductRepository savingProductRepository) {
this.savingProductRepository = savingProductRepository;
}
public SavingProductRelatedDetail assembleFrom(CalculateSavingScheduleCommand command) { private final SavingProductRepository savingProductRepository;
final BigDecimal depositAmountForPeriod = command.getDeposit(); @Autowired
final BigDecimal depositInterestRate = command.getInterestRate(); public SavingProductRelatedDetailAssembler(final SavingProductRepository savingProductRepository) {
final LocalDate installmentDate = command.getPaymentsStartingFromDate(); this.savingProductRepository = savingProductRepository;
final Integer payEvery = command.getPayEvery(); }
final Integer paymentFrequencyType = command.getPaymentFrequencyType();
final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId()); public SavingProductRelatedDetail assembleFrom(CalculateSavingScheduleCommand command) {
if (savingProduct == null) {
throw new SavingProductNotFoundException(command.getProductId()); final BigDecimal depositAmountForPeriod = command.getDeposit();
} final BigDecimal depositInterestRate = command.getInterestRate();
final LocalDate installmentDate = command.getPaymentsStartingFromDate();
final MonetaryCurrency currency = savingProduct.getCurrency(); final Integer payEvery = command.getPayEvery();
final Integer paymentFrequencyType = command.getPaymentFrequencyType();
return null; final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId());
} if (savingProduct == null) { throw new SavingProductNotFoundException(command.getProductId()); }
final MonetaryCurrency currency = savingProduct.getCurrency();
return null;
}
} }
@@ -17,42 +17,35 @@ import org.mifosplatform.portfolio.savingsaccount.domain.DepositScheduleDateGene
import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct; import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct;
public class SavingScheduleGenerator { public class SavingScheduleGenerator {
private final DepositScheduleDateGenerator scheduledDateGenerator = new DefaultDepositScheduleDateGenerator();
public SavingScheduleData generate( private final DepositScheduleDateGenerator scheduledDateGenerator = new DefaultDepositScheduleDateGenerator();
final LocalDate scheduleStartDate,
final BigDecimal depositAmountPerPeriod, public SavingScheduleData generate(final LocalDate scheduleStartDate, final BigDecimal depositAmountPerPeriod,
final Integer depositFrequency, final Integer depositFrequency, final PeriodFrequencyType depositFrequencyType, final SavingProduct savingProduct,
final PeriodFrequencyType depositFrequencyType, final Integer tenure, final ApplicationCurrency applicationCurrency) {
final SavingProduct savingProduct,
final Integer tenure, LocalDate startDate = scheduleStartDate;
final ApplicationCurrency applicationCurrency) { int periodNumber = 1;
LocalDate startDate = scheduleStartDate; Integer paymentPeriods = tenure / depositFrequency;
int periodNumber = 1; final Collection<SavingSchedulePeriodData> periods = new ArrayList<SavingSchedulePeriodData>();
final List<LocalDate> scheduledDates = this.scheduledDateGenerator.generate(startDate, paymentPeriods, depositFrequency,
Integer paymentPeriods = tenure/depositFrequency; depositFrequencyType);
final Collection<SavingSchedulePeriodData> periods = new ArrayList<SavingSchedulePeriodData>(); final MonetaryCurrency currency = savingProduct.getCurrency();
final List<LocalDate> scheduledDates = this.scheduledDateGenerator.generate(startDate,paymentPeriods,depositFrequency,depositFrequencyType); final Money depositAmount = Money.of(currency, depositAmountPerPeriod);
final MonetaryCurrency currency = savingProduct.getCurrency(); Money totalDeposit = Money.zero(currency);
final Money depositAmount = Money.of(currency, depositAmountPerPeriod);
Money totalDeposit = Money.zero(currency); for (LocalDate scheduleDate : scheduledDates) {
totalDeposit = totalDeposit.plus(depositAmount);
for(LocalDate scheduleDate : scheduledDates){ SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(periodNumber, scheduleDate,
totalDeposit = totalDeposit.plus(depositAmount); depositAmount.getAmount());
SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(periodNumber, scheduleDate, depositAmount.getAmount()); periods.add(installment);
periods.add(installment); periodNumber++;
periodNumber++; }
} CurrencyData currencyData = new CurrencyData(applicationCurrency.getCode(), applicationCurrency.getName(),
CurrencyData currencyData = new CurrencyData( currency.getDigitsAfterDecimal(), applicationCurrency.getDisplaySymbol(), applicationCurrency.getNameCode());
applicationCurrency.getCode(),
applicationCurrency.getName(), return new SavingScheduleData(currencyData, totalDeposit.getAmount(), periods);
currency.getDigitsAfterDecimal(), }
applicationCurrency.getDisplaySymbol(),
applicationCurrency.getNameCode());
return new SavingScheduleData(currencyData, totalDeposit.getAmount(), periods);
}
} }
@@ -46,165 +46,168 @@ import org.springframework.stereotype.Component;
@Component @Component
@Scope("singleton") @Scope("singleton")
public class SavingProductsApiResource { public class SavingProductsApiResource {
@Autowired
private SavingProductReadPlatformService savingProductReadPlatformService;
@Autowired
private SavingProductWritePlatformService savingProductWritePlatformService;
@Autowired @Autowired
private PortfolioApiDataConversionService apiDataConversionService; private SavingProductReadPlatformService savingProductReadPlatformService;
@Autowired
private SavingProductWritePlatformService savingProductWritePlatformService;
@Autowired
private PortfolioApiDataConversionService apiDataConversionService;
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
@Autowired @Autowired
private CurrencyReadPlatformService currencyReadPlatformService; private CurrencyReadPlatformService currencyReadPlatformService;
private final String entityType = "SAVINGSPRODUCT"; private final String entityType = "SAVINGSPRODUCT";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createSavingProduct(final String jsonRequestBody){
final SavingProductCommand command=this.apiDataConversionService.convertJsonToSavingProductCommand(null, jsonRequestBody);
EntityIdentifier entityIdentifier=this.savingProductWritePlatformService.createSavingProduct(command);
return Response.ok().entity(entityIdentifier).build();
}
@PUT
@Path("{productId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateSavingProduct(@PathParam("productId") final Long productId, final String jsonRequestBody){
SavingProductCommand command=this.apiDataConversionService.convertJsonToSavingProductCommand(productId, jsonRequestBody);
EntityIdentifier entityIdentifier=this.savingProductWritePlatformService.updateSavingProduct(command);
return Response.ok().entity(entityIdentifier).build();
}
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveAllSavingProducts(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); @POST
@Consumes({ MediaType.APPLICATION_JSON })
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", @Produces({ MediaType.APPLICATION_JSON })
"locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate", "minInterestRate","maxInterestRate", public Response createSavingProduct(final String jsonRequestBody) {
"savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod",
"minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<SavingProductData> products = this.savingProductReadPlatformService.retrieveAllSavingProducts(); final SavingProductCommand command = this.apiDataConversionService.convertJsonToSavingProductCommand(null, jsonRequestBody);
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, products);
}
@GET
@Path("{productId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveSavingProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); EntityIdentifier entityIdentifier = this.savingProductWritePlatformService.createSavingProduct(command);
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn",
"locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate", "minInterestRate","maxInterestRate",
"savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod",
"minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
if (template) {
responseParameters.addAll(Arrays.asList("currencyOptions"));
}
SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveSavingProduct(productId);
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct);
}
@GET
@Path("template")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveNewSavingProductDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); return Response.ok().entity(entityIdentifier).build();
}
Set<String> typicalResponseParameters = new HashSet<String>(
Arrays.asList("id", "createdOn", "lastModifedOn",
"locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate",
"savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod",
"minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType","currencyOptions"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveNewSavingProductDetails(); @PUT
savingProduct = handleTemplateRelatedData(responseParameters,savingProduct); @Path("{productId}")
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct); @Consumes({ MediaType.APPLICATION_JSON })
} @Produces({ MediaType.APPLICATION_JSON })
public Response updateSavingProduct(@PathParam("productId") final Long productId, final String jsonRequestBody) {
private SavingProductData handleTemplateRelatedData(Set<String> responseParameters, SavingProductData savingProduct) {
responseParameters.addAll(Arrays.asList("currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions", "savingFrequencyOptions", "savingsInterestTypeOptions",
"lockinPeriodTypeOptions", "interestCalculationOptions"));
List<CurrencyData> currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies();
EnumOptionData reccuring = SavingProductEnumerations.savingProductType(SavingProductType.RECCURING);
EnumOptionData regular = SavingProductEnumerations.savingProductType(SavingProductType.REGULAR);
List<EnumOptionData> savingsProductTypeOptions = Arrays.asList(reccuring,regular);
EnumOptionData fixed = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD);
EnumOptionData perpetual = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.PERPETUAL);
List<EnumOptionData> tenureTypeOptions = Arrays.asList(fixed,perpetual);
EnumOptionData monthly = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY);
List<EnumOptionData> savingFrequencyOptions = Arrays.asList(monthly);
EnumOptionData simple = SavingProductEnumerations.savingInterestType(SavingsInterestType.SIMPLE);
EnumOptionData compounding = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING);
List<EnumOptionData> savingsInterestTypeOptions = Arrays.asList(simple,compounding);
EnumOptionData months = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS);
List<EnumOptionData> lockinPeriodTypeOptions = Arrays.asList(months);
EnumOptionData averagebal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL);
EnumOptionData minbal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MINBAL);
EnumOptionData monthlyCollection = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MONTHLYCOLLECTION);
List<EnumOptionData> interestCalculationOptions= Arrays.asList(averagebal,minbal,monthlyCollection);
return new SavingProductData(savingProduct,currencyOptions,savingsProductTypeOptions,tenureTypeOptions,savingFrequencyOptions,savingsInterestTypeOptions,lockinPeriodTypeOptions,interestCalculationOptions);
}
@DELETE SavingProductCommand command = this.apiDataConversionService.convertJsonToSavingProductCommand(productId, jsonRequestBody);
@Path("{productId}") EntityIdentifier entityIdentifier = this.savingProductWritePlatformService.updateSavingProduct(command);
@Consumes({MediaType.APPLICATION_JSON}) return Response.ok().entity(entityIdentifier).build();
@Produces({MediaType.APPLICATION_JSON}) }
public Response deleteProduct(@PathParam("productId") final Long productId) {
this.savingProductWritePlatformService.deleteSavingProduct(productId); @GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveAllSavingProducts(@Context final UriInfo uriInfo) {
return Response.ok(new EntityIdentifier(productId)).build(); context.authenticatedUser().validateHasReadPermission(entityType);
}
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", "locale", "name",
"description", "currencyCode", "digitsAfterDecimal", "interstRate", "minInterestRate", "maxInterestRate",
"savingsDepositAmount", "savingProductType", "tenureType", "tenure", "frequency", "interestType",
"interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "isLockinPeriodAllowed",
"lockinPeriod", "lockinPeriodType"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<SavingProductData> products = this.savingProductReadPlatformService.retrieveAllSavingProducts();
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, products);
}
@GET
@Path("{productId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveSavingProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", "locale", "name",
"description", "currencyCode", "digitsAfterDecimal", "interstRate", "minInterestRate", "maxInterestRate",
"savingsDepositAmount", "savingProductType", "tenureType", "tenure", "frequency", "interestType",
"interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "isLockinPeriodAllowed",
"lockinPeriod", "lockinPeriodType"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
if (template) {
responseParameters.addAll(Arrays.asList("currencyOptions"));
}
SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveSavingProduct(productId);
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct);
}
@GET
@Path("template")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveNewSavingProductDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", "locale", "name",
"description", "currencyCode", "digitsAfterDecimal", "interstRate", "savingsDepositAmount", "savingProductType",
"tenureType", "tenure", "frequency", "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal",
"isPartialDepositAllowed", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "currencyOptions"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveNewSavingProductDetails();
savingProduct = handleTemplateRelatedData(responseParameters, savingProduct);
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct);
}
private SavingProductData handleTemplateRelatedData(Set<String> responseParameters, SavingProductData savingProduct) {
responseParameters.addAll(Arrays.asList("currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions",
"savingFrequencyOptions", "savingsInterestTypeOptions", "lockinPeriodTypeOptions", "interestCalculationOptions"));
List<CurrencyData> currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies();
EnumOptionData reccuring = SavingProductEnumerations.savingProductType(SavingProductType.RECCURING);
EnumOptionData regular = SavingProductEnumerations.savingProductType(SavingProductType.REGULAR);
List<EnumOptionData> savingsProductTypeOptions = Arrays.asList(reccuring, regular);
EnumOptionData fixed = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD);
EnumOptionData perpetual = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.PERPETUAL);
List<EnumOptionData> tenureTypeOptions = Arrays.asList(fixed, perpetual);
EnumOptionData monthly = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY);
List<EnumOptionData> savingFrequencyOptions = Arrays.asList(monthly);
EnumOptionData simple = SavingProductEnumerations.savingInterestType(SavingsInterestType.SIMPLE);
EnumOptionData compounding = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING);
List<EnumOptionData> savingsInterestTypeOptions = Arrays.asList(simple, compounding);
EnumOptionData months = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS);
List<EnumOptionData> lockinPeriodTypeOptions = Arrays.asList(months);
EnumOptionData averagebal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL);
EnumOptionData minbal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MINBAL);
EnumOptionData monthlyCollection = SavingProductEnumerations
.savingInterestCalculationMethod(SavingInterestCalculationMethod.MONTHLYCOLLECTION);
List<EnumOptionData> interestCalculationOptions = Arrays.asList(averagebal, minbal, monthlyCollection);
return new SavingProductData(savingProduct, currencyOptions, savingsProductTypeOptions, tenureTypeOptions, savingFrequencyOptions,
savingsInterestTypeOptions, lockinPeriodTypeOptions, interestCalculationOptions);
}
@DELETE
@Path("{productId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response deleteProduct(@PathParam("productId") final Long productId) {
this.savingProductWritePlatformService.deleteSavingProduct(productId);
return Response.ok(new EntityIdentifier(productId)).build();
}
} }
@@ -4,216 +4,210 @@ import java.math.BigDecimal;
import java.util.Set; import java.util.Set;
public class SavingProductCommand { public class SavingProductCommand {
private final Long id;
private final String name;
private final String description;
private final String currencyCode; private final Long id;
private final Integer digitsAfterDecimal; private final String name;
private final BigDecimal interestRate; private final String description;
private final BigDecimal minInterestRate;
private final BigDecimal maxInterestRate;
private final BigDecimal savingsDepositAmount;
private final Integer savingProductType;
private final Integer tenureType;
private final Integer tenure;
private final Integer frequency;
private final Integer interestType;
private final Integer interestCalculationMethod;
private final BigDecimal minimumBalanceForWithdrawal;
private final boolean isPartialDepositAllowed;
private final boolean isLockinPeriodAllowed;
private final Integer lockinPeriod;
private final Integer lockinPeriodType;
private final Set<String> modifiedParameters; private final String currencyCode;
private final Integer digitsAfterDecimal;
public SavingProductCommand(Set<String> modifiedParameters, private final BigDecimal interestRate;
Long id, String name, String description, private final BigDecimal minInterestRate;
String currencyCode, Integer digitsAfterDecimal, private final BigDecimal maxInterestRate;
BigDecimal interestRate, BigDecimal minInterestRate,
BigDecimal maxInterestRate, BigDecimal savingsDepositAmount,
Integer savingProductType, Integer tenureType, Integer tenure,
Integer frequency, Integer interestType,
Integer interestCalculationMethod,
BigDecimal minimumBalanceForWithdrawal,
boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed,
Integer lockinPeriod, Integer lockinPeriodType) {
this.id = id;
this.name = name;
this.description = description;
this.currencyCode = currencyCode; private final BigDecimal savingsDepositAmount;
this.digitsAfterDecimal = digitsAfterDecimal; private final Integer savingProductType;
this.interestRate = interestRate; private final Integer tenureType;
this.minInterestRate = minInterestRate; private final Integer tenure;
this.maxInterestRate = maxInterestRate; private final Integer frequency;
private final Integer interestType;
this.savingsDepositAmount=savingsDepositAmount; private final Integer interestCalculationMethod;
this.savingProductType=savingProductType; private final BigDecimal minimumBalanceForWithdrawal;
this.tenureType=tenureType; private final boolean isPartialDepositAllowed;
this.tenure=tenure; private final boolean isLockinPeriodAllowed;
this.frequency=frequency; private final Integer lockinPeriod;
this.interestType=interestType; private final Integer lockinPeriodType;
this.interestCalculationMethod=interestCalculationMethod;
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal;
this.isPartialDepositAllowed=isPartialDepositAllowed;
this.isLockinPeriodAllowed=isLockinPeriodAllowed;
this.lockinPeriod=lockinPeriod;
this.lockinPeriodType=lockinPeriodType;
this.modifiedParameters = modifiedParameters; private final Set<String> modifiedParameters;
}
public Long getId() { public SavingProductCommand(Set<String> modifiedParameters, Long id, String name, String description, String currencyCode,
return id; Integer digitsAfterDecimal, BigDecimal interestRate, BigDecimal minInterestRate, BigDecimal maxInterestRate,
} BigDecimal savingsDepositAmount, Integer savingProductType, Integer tenureType, Integer tenure, Integer frequency,
Integer interestType, Integer interestCalculationMethod, BigDecimal minimumBalanceForWithdrawal,
boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, Integer lockinPeriod, Integer lockinPeriodType) {
public String getName() { this.id = id;
return name; this.name = name;
} this.description = description;
public String getDescription() { this.currencyCode = currencyCode;
return description; this.digitsAfterDecimal = digitsAfterDecimal;
} this.interestRate = interestRate;
this.minInterestRate = minInterestRate;
this.maxInterestRate = maxInterestRate;
public String getCurrencyCode() { this.savingsDepositAmount = savingsDepositAmount;
return currencyCode; this.savingProductType = savingProductType;
} this.tenureType = tenureType;
this.tenure = tenure;
this.frequency = frequency;
this.interestType = interestType;
this.interestCalculationMethod = interestCalculationMethod;
this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.isPartialDepositAllowed = isPartialDepositAllowed;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
public Integer getDigitsAfterDecimal() { this.modifiedParameters = modifiedParameters;
return digitsAfterDecimal; }
}
public BigDecimal getInterestRate() { public Long getId() {
return interestRate; return id;
} }
public BigDecimal getMinInterestRate() { public String getName() {
return minInterestRate; return name;
} }
public BigDecimal getMaxInterestRate() { public String getDescription() {
return maxInterestRate; return description;
} }
public BigDecimal getSavingsDepositAmount() { public String getCurrencyCode() {
return savingsDepositAmount; return currencyCode;
} }
public Integer getSavingProductType() { public Integer getDigitsAfterDecimal() {
return savingProductType; return digitsAfterDecimal;
} }
public Integer getTenureType() { public BigDecimal getInterestRate() {
return tenureType; return interestRate;
} }
public Integer getTenure() { public BigDecimal getMinInterestRate() {
return tenure; return minInterestRate;
} }
public Integer getFrequency() { public BigDecimal getMaxInterestRate() {
return frequency; return maxInterestRate;
} }
public Integer getInterestType() { public BigDecimal getSavingsDepositAmount() {
return interestType; return savingsDepositAmount;
} }
public Integer getInterestCalculationMethod() { public Integer getSavingProductType() {
return interestCalculationMethod; return savingProductType;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public Integer getTenureType() {
return minimumBalanceForWithdrawal; return tenureType;
} }
public boolean isPartialDepositAllowed() { public Integer getTenure() {
return isPartialDepositAllowed; return tenure;
} }
public boolean isLockinPeriodAllowed() { public Integer getFrequency() {
return isLockinPeriodAllowed; return frequency;
} }
public Integer getLockinPeriod() { public Integer getInterestType() {
return lockinPeriod; return interestType;
} }
public Integer getLockinPeriodType() { public Integer getInterestCalculationMethod() {
return lockinPeriodType; return interestCalculationMethod;
} }
public boolean isNameChanged() { public BigDecimal getMinimumBalanceForWithdrawal() {
return this.modifiedParameters.contains("name"); return minimumBalanceForWithdrawal;
} }
public boolean isDescriptionChanged() { public boolean isPartialDepositAllowed() {
return this.modifiedParameters.contains("description"); return isPartialDepositAllowed;
} }
public boolean isCurrencyCodeChanged() {
return this.modifiedParameters.contains("currencyCode");
}
public boolean isDigitsAfterDecimalChanged() { public boolean isLockinPeriodAllowed() {
return this.modifiedParameters.contains("digitsAfterDecimal"); return isLockinPeriodAllowed;
} }
public boolean isInterestRateChanged() {
return this.modifiedParameters.contains("interestRate");
}
public boolean isSavingsDepositAmountChanged(){
return this.modifiedParameters.contains("savingsDepositAmount");
}
public boolean isSavingProductTypeChanged() {
return this.modifiedParameters.contains("savingProductType");
}
public boolean isTenureTypeChanged() { public Integer getLockinPeriod() {
return this.modifiedParameters.contains("tenureType"); return lockinPeriod;
} }
public boolean isTenureChanged() { public Integer getLockinPeriodType() {
return this.modifiedParameters.contains("tenure"); return lockinPeriodType;
} }
public boolean isFrequencyChanged() { public boolean isNameChanged() {
return this.modifiedParameters.contains("frequency"); return this.modifiedParameters.contains("name");
} }
public boolean isInterestTypeChanged() { public boolean isDescriptionChanged() {
return this.modifiedParameters.contains("interestType"); return this.modifiedParameters.contains("description");
} }
public boolean isInterestCalculationMethodChanged() { public boolean isCurrencyCodeChanged() {
return this.modifiedParameters.contains("interestCalculationMethod"); return this.modifiedParameters.contains("currencyCode");
} }
public boolean isMinimumBalanceForWithdrawalChanged() { public boolean isDigitsAfterDecimalChanged() {
return this.modifiedParameters.contains("minimumBalanceForWithdrawal"); return this.modifiedParameters.contains("digitsAfterDecimal");
} }
public boolean isPartialDepositAllowedChanged() { public boolean isInterestRateChanged() {
return this.modifiedParameters.contains("isPartialDepositAllowed"); return this.modifiedParameters.contains("interestRate");
} }
public boolean isLockinPeriodAllowedChanged() { public boolean isSavingsDepositAmountChanged() {
return this.modifiedParameters.contains("isLockinPeriodAllowed"); return this.modifiedParameters.contains("savingsDepositAmount");
} }
public boolean isLockinPeriodChanged() { public boolean isSavingProductTypeChanged() {
return this.modifiedParameters.contains("lockinPeriod"); return this.modifiedParameters.contains("savingProductType");
} }
public boolean isTenureTypeChanged() {
return this.modifiedParameters.contains("tenureType");
}
public boolean isTenureChanged() {
return this.modifiedParameters.contains("tenure");
}
public boolean isFrequencyChanged() {
return this.modifiedParameters.contains("frequency");
}
public boolean isInterestTypeChanged() {
return this.modifiedParameters.contains("interestType");
}
public boolean isInterestCalculationMethodChanged() {
return this.modifiedParameters.contains("interestCalculationMethod");
}
public boolean isMinimumBalanceForWithdrawalChanged() {
return this.modifiedParameters.contains("minimumBalanceForWithdrawal");
}
public boolean isPartialDepositAllowedChanged() {
return this.modifiedParameters.contains("isPartialDepositAllowed");
}
public boolean isLockinPeriodAllowedChanged() {
return this.modifiedParameters.contains("isLockinPeriodAllowed");
}
public boolean isLockinPeriodChanged() {
return this.modifiedParameters.contains("lockinPeriod");
}
public boolean isLockinPeriodTypeChanged() {
return this.modifiedParameters.contains("lockinPeriodType");
}
public boolean isLockinPeriodTypeChanged() {
return this.modifiedParameters.contains("lockinPeriodType");
}
} }
@@ -11,260 +11,250 @@ import org.mifosplatform.organisation.monetary.data.CurrencyData;
public class SavingProductData implements Serializable { public class SavingProductData implements Serializable {
private final Long id; private final Long id;
private final String name; private final String name;
private final String description; private final String description;
private final CurrencyData currency; private final CurrencyData currency;
private final Integer digitsAfterDecimal; private final Integer digitsAfterDecimal;
private final BigDecimal interestRate;
private final BigDecimal minInterestRate;
private final BigDecimal maxInterestRate;
private final BigDecimal savingsDepositAmount;
private final EnumOptionData savingProductType;
private final EnumOptionData tenureType;
private final Integer tenure;
private final EnumOptionData savingFrequencyType;
private final EnumOptionData interestType;
private final EnumOptionData interestCalculationMethod;
private final BigDecimal minimumBalanceForWithdrawal;
private final boolean isPartialDepositAllowed;
private final boolean isLockinPeriodAllowed;
private final Integer lockinPeriod;
private final EnumOptionData lockinPeriodType;
private DateTime createdOn;
private DateTime lastModifedOn;
private List<CurrencyData> currencyOptions = new ArrayList<CurrencyData>();
List<EnumOptionData> savingsProductTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> tenureTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> savingFrequencyOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> savingsInterestTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> lockinPeriodTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> interestCalculationOptions = new ArrayList<EnumOptionData>();
public SavingProductData(){
this.createdOn=new DateTime();
this.lastModifedOn=new DateTime();
this.id=null;
this.name=null;
this.description=null;
this.interestRate=BigDecimal.ZERO;
this.minInterestRate=BigDecimal.ZERO;
this.maxInterestRate=BigDecimal.ZERO;
this.currency=null;
this.digitsAfterDecimal=null;
this.savingsDepositAmount=null;
this.savingProductType=null;
this.tenureType = null;
this.tenure = null;
this.savingFrequencyType=null;
this.interestType=null;
this.interestCalculationMethod=null;
this.minimumBalanceForWithdrawal=null;
this.isPartialDepositAllowed=true;
this.isLockinPeriodAllowed=true;
this.lockinPeriod=null;
this.lockinPeriodType=null;
}
public SavingProductData(DateTime createdOn, DateTime lastModifedOn, private final BigDecimal interestRate;
Long id, String name, String description, private final BigDecimal minInterestRate;
BigDecimal interestRate, BigDecimal minInterestRate, BigDecimal maxInterestRate, CurrencyData currency, private final BigDecimal maxInterestRate;
Integer digitsAfterDecimal, BigDecimal savingsDepositAmount, private final BigDecimal savingsDepositAmount;
EnumOptionData savingProductType, private final EnumOptionData savingProductType;
EnumOptionData tenureType, Integer tenure, private final EnumOptionData tenureType;
EnumOptionData savingFrequencyType, private final Integer tenure;
EnumOptionData savingInterestType, private final EnumOptionData savingFrequencyType;
EnumOptionData interestCalculationMethod, private final EnumOptionData interestType;
BigDecimal minimumBalanceForWithdrawal, private final EnumOptionData interestCalculationMethod;
boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, private final BigDecimal minimumBalanceForWithdrawal;
Integer lockinPeriod, EnumOptionData lockinPeriodType) { private final boolean isPartialDepositAllowed;
this.createdOn=createdOn; private final boolean isLockinPeriodAllowed;
this.lastModifedOn=lastModifedOn; private final Integer lockinPeriod;
this.id=id; private final EnumOptionData lockinPeriodType;
this.name=name;
this.description=description;
this.interestRate=interestRate;
this.minInterestRate=minInterestRate;
this.maxInterestRate=maxInterestRate;
this.currency=currency;
this.digitsAfterDecimal=digitsAfterDecimal;
this.savingsDepositAmount=savingsDepositAmount;
this.savingProductType=savingProductType;
this.tenureType = tenureType;
this.tenure = tenure;
this.savingFrequencyType=savingFrequencyType;
this.interestType=savingInterestType;
this.interestCalculationMethod=interestCalculationMethod;
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal;
this.isPartialDepositAllowed=isPartialDepositAllowed;
this.isLockinPeriodAllowed=isLockinPeriodAllowed;
this.lockinPeriod=lockinPeriod;
this.lockinPeriodType=lockinPeriodType;
}
public SavingProductData(SavingProductData product, private DateTime createdOn;
List<CurrencyData> currencyOptions, private DateTime lastModifedOn;
List<EnumOptionData> savingsProductTypeOptions,
List<EnumOptionData> tenureTypeOptions,
List<EnumOptionData> savingFrequencyOptions,
List<EnumOptionData> savingsInterestTypeOptions,
List<EnumOptionData> lockinPeriodTypeOptions,
List<EnumOptionData> interestCalculationOptions) {
this.createdOn=product.getCreatedOn();
this.lastModifedOn=product.getLastModifedOn();
this.id=product.getId();
this.name=product.getName();
this.description=product.getDescription();
this.interestRate=product.getInterestRate();
this.minInterestRate=product.getMinInterestRate();
this.maxInterestRate=product.getMaxInterestRate();
this.currency=product.getCurrency();
this.digitsAfterDecimal=product.getDigitsAfterDecimal();
this.savingsDepositAmount=product.getSavingsDepositAmount();
this.savingProductType=product.getSavingProductType();
this.tenureType = product.getTenureType();
this.tenure = product.getTenure();
this.savingFrequencyType=product.getSavingFrequencyType();
this.interestType=product.getInterestType();
this.interestCalculationMethod=product.getInterestCalculationMethod();
this.minimumBalanceForWithdrawal=product.getMinimumBalanceForWithdrawal();
this.isPartialDepositAllowed=product.isPartialDepositAllowed();
this.isLockinPeriodAllowed=product.isLockinPeriodAllowed();
this.lockinPeriod=product.getLockinPeriod();
this.lockinPeriodType=product.getLockinPeriodType();
this.currencyOptions=currencyOptions;
this.savingsProductTypeOptions=savingsProductTypeOptions;
this.tenureTypeOptions=tenureTypeOptions;
this.savingFrequencyOptions=savingFrequencyOptions;
this.savingsInterestTypeOptions=savingsInterestTypeOptions;
this.lockinPeriodTypeOptions=lockinPeriodTypeOptions;
this.interestCalculationOptions=interestCalculationOptions;
}
public Long getId() { private List<CurrencyData> currencyOptions = new ArrayList<CurrencyData>();
return id; List<EnumOptionData> savingsProductTypeOptions = new ArrayList<EnumOptionData>();
} List<EnumOptionData> tenureTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> savingFrequencyOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> savingsInterestTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> lockinPeriodTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> interestCalculationOptions = new ArrayList<EnumOptionData>();
public String getName() { public SavingProductData() {
return name; this.createdOn = new DateTime();
} this.lastModifedOn = new DateTime();
this.id = null;
this.name = null;
this.description = null;
this.interestRate = BigDecimal.ZERO;
this.minInterestRate = BigDecimal.ZERO;
this.maxInterestRate = BigDecimal.ZERO;
this.currency = null;
this.digitsAfterDecimal = null;
this.savingsDepositAmount = null;
this.savingProductType = null;
this.tenureType = null;
this.tenure = null;
this.savingFrequencyType = null;
this.interestType = null;
this.interestCalculationMethod = null;
this.minimumBalanceForWithdrawal = null;
this.isPartialDepositAllowed = true;
this.isLockinPeriodAllowed = true;
this.lockinPeriod = null;
this.lockinPeriodType = null;
}
public String getDescription() { public SavingProductData(DateTime createdOn, DateTime lastModifedOn, Long id, String name, String description, BigDecimal interestRate,
return description; BigDecimal minInterestRate, BigDecimal maxInterestRate, CurrencyData currency, Integer digitsAfterDecimal,
} BigDecimal savingsDepositAmount, EnumOptionData savingProductType, EnumOptionData tenureType, Integer tenure,
EnumOptionData savingFrequencyType, EnumOptionData savingInterestType, EnumOptionData interestCalculationMethod,
BigDecimal minimumBalanceForWithdrawal, boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, Integer lockinPeriod,
EnumOptionData lockinPeriodType) {
this.createdOn = createdOn;
this.lastModifedOn = lastModifedOn;
this.id = id;
this.name = name;
this.description = description;
this.interestRate = interestRate;
this.minInterestRate = minInterestRate;
this.maxInterestRate = maxInterestRate;
this.currency = currency;
this.digitsAfterDecimal = digitsAfterDecimal;
this.savingsDepositAmount = savingsDepositAmount;
this.savingProductType = savingProductType;
this.tenureType = tenureType;
this.tenure = tenure;
this.savingFrequencyType = savingFrequencyType;
this.interestType = savingInterestType;
this.interestCalculationMethod = interestCalculationMethod;
this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.isPartialDepositAllowed = isPartialDepositAllowed;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
}
public CurrencyData getCurrency() { public SavingProductData(SavingProductData product, List<CurrencyData> currencyOptions, List<EnumOptionData> savingsProductTypeOptions,
return currency; List<EnumOptionData> tenureTypeOptions, List<EnumOptionData> savingFrequencyOptions,
} List<EnumOptionData> savingsInterestTypeOptions, List<EnumOptionData> lockinPeriodTypeOptions,
List<EnumOptionData> interestCalculationOptions) {
public Integer getDigitsAfterDecimal() {
return digitsAfterDecimal;
}
public BigDecimal getInterestRate() { this.createdOn = product.getCreatedOn();
return interestRate; this.lastModifedOn = product.getLastModifedOn();
} this.id = product.getId();
this.name = product.getName();
this.description = product.getDescription();
this.interestRate = product.getInterestRate();
this.minInterestRate = product.getMinInterestRate();
this.maxInterestRate = product.getMaxInterestRate();
this.currency = product.getCurrency();
this.digitsAfterDecimal = product.getDigitsAfterDecimal();
this.savingsDepositAmount = product.getSavingsDepositAmount();
this.savingProductType = product.getSavingProductType();
this.tenureType = product.getTenureType();
this.tenure = product.getTenure();
this.savingFrequencyType = product.getSavingFrequencyType();
this.interestType = product.getInterestType();
this.interestCalculationMethod = product.getInterestCalculationMethod();
this.minimumBalanceForWithdrawal = product.getMinimumBalanceForWithdrawal();
this.isPartialDepositAllowed = product.isPartialDepositAllowed();
this.isLockinPeriodAllowed = product.isLockinPeriodAllowed();
this.lockinPeriod = product.getLockinPeriod();
this.lockinPeriodType = product.getLockinPeriodType();
public BigDecimal getMinInterestRate() { this.currencyOptions = currencyOptions;
return minInterestRate; this.savingsProductTypeOptions = savingsProductTypeOptions;
} this.tenureTypeOptions = tenureTypeOptions;
this.savingFrequencyOptions = savingFrequencyOptions;
this.savingsInterestTypeOptions = savingsInterestTypeOptions;
this.lockinPeriodTypeOptions = lockinPeriodTypeOptions;
this.interestCalculationOptions = interestCalculationOptions;
public BigDecimal getMaxInterestRate() { }
return maxInterestRate;
}
public BigDecimal getSavingsDepositAmount() { public Long getId() {
return savingsDepositAmount; return id;
} }
public EnumOptionData getSavingProductType() { public String getName() {
return savingProductType; return name;
} }
public EnumOptionData getTenureType() { public String getDescription() {
return tenureType; return description;
} }
public Integer getTenure() { public CurrencyData getCurrency() {
return tenure; return currency;
} }
public EnumOptionData getInterestType() { public Integer getDigitsAfterDecimal() {
return interestType; return digitsAfterDecimal;
} }
public EnumOptionData getInterestCalculationMethod() { public BigDecimal getInterestRate() {
return interestCalculationMethod; return interestRate;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public BigDecimal getMinInterestRate() {
return minimumBalanceForWithdrawal; return minInterestRate;
} }
public boolean isPartialDepositAllowed() { public BigDecimal getMaxInterestRate() {
return isPartialDepositAllowed; return maxInterestRate;
} }
public boolean isLockinPeriodAllowed() { public BigDecimal getSavingsDepositAmount() {
return isLockinPeriodAllowed; return savingsDepositAmount;
} }
public Integer getLockinPeriod() { public EnumOptionData getSavingProductType() {
return lockinPeriod; return savingProductType;
} }
public EnumOptionData getLockinPeriodType() { public EnumOptionData getTenureType() {
return lockinPeriodType; return tenureType;
} }
public DateTime getCreatedOn() { public Integer getTenure() {
return createdOn; return tenure;
} }
public DateTime getLastModifedOn() { public EnumOptionData getInterestType() {
return lastModifedOn; return interestType;
} }
public List<CurrencyData> getCurrencyOptions() { public EnumOptionData getInterestCalculationMethod() {
return currencyOptions; return interestCalculationMethod;
} }
public void setCurrencyOptions(List<CurrencyData> currencyOptions) { public BigDecimal getMinimumBalanceForWithdrawal() {
this.currencyOptions = currencyOptions; return minimumBalanceForWithdrawal;
} }
public EnumOptionData getSavingFrequencyType() { public boolean isPartialDepositAllowed() {
return savingFrequencyType; return isPartialDepositAllowed;
} }
public List<EnumOptionData> getSavingsProductTypeOptions() { public boolean isLockinPeriodAllowed() {
return savingsProductTypeOptions; return isLockinPeriodAllowed;
} }
public List<EnumOptionData> getTenureTypeOptions() { public Integer getLockinPeriod() {
return tenureTypeOptions; return lockinPeriod;
} }
public List<EnumOptionData> getSavingFrequencyOptions() { public EnumOptionData getLockinPeriodType() {
return savingFrequencyOptions; return lockinPeriodType;
} }
public List<EnumOptionData> getSavingsInterestTypeOptions() { public DateTime getCreatedOn() {
return savingsInterestTypeOptions; return createdOn;
} }
public List<EnumOptionData> getLockinPeriodTypeOptions() { public DateTime getLastModifedOn() {
return lockinPeriodTypeOptions; return lastModifedOn;
} }
public List<CurrencyData> getCurrencyOptions() {
return currencyOptions;
}
public void setCurrencyOptions(List<CurrencyData> currencyOptions) {
this.currencyOptions = currencyOptions;
}
public EnumOptionData getSavingFrequencyType() {
return savingFrequencyType;
}
public List<EnumOptionData> getSavingsProductTypeOptions() {
return savingsProductTypeOptions;
}
public List<EnumOptionData> getTenureTypeOptions() {
return tenureTypeOptions;
}
public List<EnumOptionData> getSavingFrequencyOptions() {
return savingFrequencyOptions;
}
public List<EnumOptionData> getSavingsInterestTypeOptions() {
return savingsInterestTypeOptions;
}
public List<EnumOptionData> getLockinPeriodTypeOptions() {
return lockinPeriodTypeOptions;
}
public List<EnumOptionData> getInterestCalculationOptions() {
return interestCalculationOptions;
}
public List<EnumOptionData> getInterestCalculationOptions() {
return interestCalculationOptions;
}
} }
@@ -3,32 +3,33 @@ package org.mifosplatform.portfolio.savingsaccountproduct.data;
import java.io.Serializable; import java.io.Serializable;
public class SavingProductLookup implements Serializable { public class SavingProductLookup implements Serializable {
private Long id;
private String name;
public SavingProductLookup() { private Long id;
// private String name;
}
public SavingProductLookup(Long id, String name) { public SavingProductLookup() {
this.id = id; //
this.name = name; }
}
public Long getId() { public SavingProductLookup(Long id, String name) {
return id; this.id = id;
} this.name = name;
}
public void setId(Long id) { public Long getId() {
this.id = id; return id;
} }
public String getName() { public void setId(Long id) {
return name; this.id = id;
} }
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public void setName(String name) {
this.name = name;
}
} }
@@ -1,54 +1,50 @@
package org.mifosplatform.portfolio.savingsaccountproduct.domain; package org.mifosplatform.portfolio.savingsaccountproduct.domain;
public enum SavingFrequencyType { public enum SavingFrequencyType {
INVALID(0,"savingFrequencyType.invalid"),
DAILY(1,"savingFrequencyType.daily"),
MONTHLY(2,"savingFrequencyType.monthly"),
QUATERLY(3,"savingFrequencyType.quaterly"),
HALFYEARLY(4,"savingFrequencyType.halfyearly"),
YEARLY(5,"savingFrequencyType.yearly");
private final Integer value;
private final String code;
private SavingFrequencyType(final Integer value,final String code) {
this.value=value;
this.code=code;
}
public Integer getValue() {
return value;
}
public String getCode() {
return code;
}
public static SavingFrequencyType fromInt(final Integer frequency) {
SavingFrequencyType savingFrequencyType = SavingFrequencyType.INVALID; INVALID(0, "savingFrequencyType.invalid"), DAILY(1, "savingFrequencyType.daily"), MONTHLY(2, "savingFrequencyType.monthly"), QUATERLY(
switch (frequency) { 3, "savingFrequencyType.quaterly"), HALFYEARLY(4, "savingFrequencyType.halfyearly"), YEARLY(5, "savingFrequencyType.yearly");
case 1:
savingFrequencyType = SavingFrequencyType.DAILY; private final Integer value;
break; private final String code;
case 2:
savingFrequencyType = SavingFrequencyType.MONTHLY; private SavingFrequencyType(final Integer value, final String code) {
break; this.value = value;
case 3: this.code = code;
savingFrequencyType = SavingFrequencyType.QUATERLY; }
break;
case 4: public Integer getValue() {
savingFrequencyType = SavingFrequencyType.HALFYEARLY; return value;
break; }
case 5:
savingFrequencyType = SavingFrequencyType.YEARLY; public String getCode() {
break; return code;
default: }
savingFrequencyType = SavingFrequencyType.INVALID;
break; public static SavingFrequencyType fromInt(final Integer frequency) {
}
return savingFrequencyType; SavingFrequencyType savingFrequencyType = SavingFrequencyType.INVALID;
} switch (frequency) {
case 1:
savingFrequencyType = SavingFrequencyType.DAILY;
break;
case 2:
savingFrequencyType = SavingFrequencyType.MONTHLY;
break;
case 3:
savingFrequencyType = SavingFrequencyType.QUATERLY;
break;
case 4:
savingFrequencyType = SavingFrequencyType.HALFYEARLY;
break;
case 5:
savingFrequencyType = SavingFrequencyType.YEARLY;
break;
default:
savingFrequencyType = SavingFrequencyType.INVALID;
break;
}
return savingFrequencyType;
}
} }
@@ -1,44 +1,43 @@
package org.mifosplatform.portfolio.savingsaccountproduct.domain; package org.mifosplatform.portfolio.savingsaccountproduct.domain;
public enum SavingInterestCalculationMethod { public enum SavingInterestCalculationMethod {
AVERAGEBAL(1,"savinginterest.calculation.method.averagebal"),
MINBAL(2,"savinginterest.calculation.method.minbal"),
MONTHLYCOLLECTION(3,"savinginterest.calculation.method.monthlycllection"),
INVALID(0,"savinginterest.calculation.method.invalid");
private final Integer value; AVERAGEBAL(1, "savinginterest.calculation.method.averagebal"), MINBAL(2, "savinginterest.calculation.method.minbal"), MONTHLYCOLLECTION(
private final String code; 3, "savinginterest.calculation.method.monthlycllection"), INVALID(0, "savinginterest.calculation.method.invalid");
private SavingInterestCalculationMethod(final Integer value,final String code) {
this.value=value;
this.code=code;
}
public Integer getValue() { private final Integer value;
return value; private final String code;
}
public String getCode() { private SavingInterestCalculationMethod(final Integer value, final String code) {
return code; this.value = value;
} this.code = code;
public static SavingInterestCalculationMethod fromInt(final Integer frequency) { }
SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID; public Integer getValue() {
switch (frequency) { return value;
case 1: }
savingInterestCalculationMethod = SavingInterestCalculationMethod.AVERAGEBAL;
break; public String getCode() {
case 2: return code;
savingInterestCalculationMethod = SavingInterestCalculationMethod.MINBAL; }
break;
case 3: public static SavingInterestCalculationMethod fromInt(final Integer frequency) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.MONTHLYCOLLECTION;
break; SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID;
default: switch (frequency) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID; case 1:
break; savingInterestCalculationMethod = SavingInterestCalculationMethod.AVERAGEBAL;
} break;
return savingInterestCalculationMethod; case 2:
} savingInterestCalculationMethod = SavingInterestCalculationMethod.MINBAL;
break;
case 3:
savingInterestCalculationMethod = SavingInterestCalculationMethod.MONTHLYCOLLECTION;
break;
default:
savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID;
break;
}
return savingInterestCalculationMethod;
}
} }
@@ -18,82 +18,87 @@ import org.mifosplatform.useradministration.domain.AppUser;
@Entity @Entity
@Table(name = "m_product_savings") @Table(name = "m_product_savings")
public class SavingProduct extends AbstractAuditableCustom<AppUser, Long> { public class SavingProduct extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "name", nullable = false)
private String name;
@Column(name = "description") @Column(name = "name", nullable = false)
private String description; private String name;
@Column(name = "is_deleted", nullable=false)
private boolean deleted = false;
@Embedded
SavingProductRelatedDetail savingProductRelatedDetail;
protected SavingProduct() { @Column(name = "description")
this.name = null; private String description;
@Column(name = "is_deleted", nullable = false)
private boolean deleted = false;
@Embedded
SavingProductRelatedDetail savingProductRelatedDetail;
protected SavingProduct() {
this.name = null;
this.description = null; this.description = null;
this.savingProductRelatedDetail = null; this.savingProductRelatedDetail = null;
} }
public SavingProduct(final String name, final String description, final MonetaryCurrency currency,final BigDecimal interestRate, final BigDecimal minInterestRate, final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount,
final SavingProductType savingProductType, final TenureTypeEnum tenureType, final Integer tenure, final SavingFrequencyType savingFrequencyType,
final SavingsInterestType savingsInterestType, SavingInterestCalculationMethod savingInterestCalculationMethod, final BigDecimal minimumBalanceForWithdrawal,
final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType){
this.name = name.trim();
if (StringUtils.isNotBlank(description)) {
this.description = description.trim();
} else {
this.description = null;
}
this.savingProductRelatedDetail = new SavingProductRelatedDetail(currency, interestRate, minInterestRate, maxInterestRate, savingsDepositAmount, savingProductType, tenureType, tenure,
savingFrequencyType, savingsInterestType, savingInterestCalculationMethod, minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType);
}
public String getName() { public SavingProduct(final String name, final String description, final MonetaryCurrency currency, final BigDecimal interestRate,
final BigDecimal minInterestRate, final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount,
final SavingProductType savingProductType, final TenureTypeEnum tenureType, final Integer tenure,
final SavingFrequencyType savingFrequencyType, final SavingsInterestType savingsInterestType,
SavingInterestCalculationMethod savingInterestCalculationMethod, final BigDecimal minimumBalanceForWithdrawal,
final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod,
final PeriodFrequencyType lockinPeriodType) {
this.name = name.trim();
if (StringUtils.isNotBlank(description)) {
this.description = description.trim();
} else {
this.description = null;
}
this.savingProductRelatedDetail = new SavingProductRelatedDetail(currency, interestRate, minInterestRate, maxInterestRate,
savingsDepositAmount, savingProductType, tenureType, tenure, savingFrequencyType, savingsInterestType,
savingInterestCalculationMethod, minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod,
lockinPeriodType);
}
public String getName() {
return this.name; return this.name;
} }
public String getDescription() { public String getDescription() {
return this.description; return this.description;
}
public MonetaryCurrency getCurrency() {
return this.savingProductRelatedDetail.getCurrency();
} }
public BigDecimal getInterestRate(){
return this.savingProductRelatedDetail.getInterestRate();
}
public BigDecimal getMinimumBalance(){
return this.savingProductRelatedDetail.getMinimumBalance();
}
public boolean isDeleted() {
return deleted;
}
public void delete() {
this.deleted = true;
}
public SavingProductRelatedDetail getSavingProductRelatedDetail() { public MonetaryCurrency getCurrency() {
return savingProductRelatedDetail; return this.savingProductRelatedDetail.getCurrency();
} }
public void update(final SavingProductCommand command) { public BigDecimal getInterestRate() {
return this.savingProductRelatedDetail.getInterestRate();
}
if (command.isNameChanged()) { public BigDecimal getMinimumBalance() {
this.name = command.getName(); return this.savingProductRelatedDetail.getMinimumBalance();
} }
if (command.isDescriptionChanged()) { public boolean isDeleted() {
this.description = command.getDescription(); return deleted;
} }
this.savingProductRelatedDetail.update(command); public void delete() {
} this.deleted = true;
}
public SavingProductRelatedDetail getSavingProductRelatedDetail() {
return savingProductRelatedDetail;
}
public void update(final SavingProductCommand command) {
if (command.isNameChanged()) {
this.name = command.getName();
}
if (command.isDescriptionChanged()) {
this.description = command.getDescription();
}
this.savingProductRelatedDetail.update(command);
}
} }
@@ -13,214 +13,212 @@ import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum;
@Embeddable @Embeddable
public class SavingProductRelatedDetail { public class SavingProductRelatedDetail {
@Embedded
private MonetaryCurrency currency;
@Column(name = "interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal interestRate;
@SuppressWarnings("unused")
@Column(name = "min_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal minInterestRate;
@SuppressWarnings("unused")
@Column(name = "max_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal maxInterestRate;
@Column(name = "savings_deposit_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal savingsDepositAmount;
@Column(name = "savings_product_type", nullable=false)
private SavingProductType savingProductType;
@Column(name = "tenure_type", nullable=false)
private TenureTypeEnum tenureType;
@Column(name = "tenure", nullable=false)
private Integer tenure;
@Column(name = "frequency", nullable=false)
private SavingFrequencyType frequency;
@Column(name = "interest_type", nullable=false)
private SavingsInterestType interestType;
@Column(name = "interest_calculation_method")
private SavingInterestCalculationMethod interestCalculationMethod;
@Column(name = "min_bal_for_withdrawal", scale = 6, precision = 19, nullable = false)
private BigDecimal minimumBalanceForWithdrawal;
@Column(name = "is_partial_deposit_allowed", nullable=false)
private boolean isPartialDepositAllowed;
@Column(name = "is_lock_in_period_allowed", nullable=false)
private boolean isLockinPeriodAllowed;
@Column(name = "lock_in_period", nullable=false)
private Integer lockinPeriod;
@Column(name = "lock_in_period_type", nullable=false)
private PeriodFrequencyType lockinPeriodType;
public SavingProductRelatedDetail() {
this.interestRate=null;
this.savingsDepositAmount=null;
}
public SavingProductRelatedDetail(final MonetaryCurrency currency,final BigDecimal interestRate, final BigDecimal minInterestRate, final BigDecimal maxInterestRate,
final BigDecimal savingsDepositAmount, final SavingProductType savingProductType,
final TenureTypeEnum tenureType, final Integer tenure,
final SavingFrequencyType frequency, final SavingsInterestType interestType,
final SavingInterestCalculationMethod interestCalculationMethod,
final BigDecimal minimumBalanceForWithdrawal,
final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed,
final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType) {
this.currency=currency;
this.interestRate=interestRate;
this.minInterestRate = minInterestRate;
this.maxInterestRate = maxInterestRate;
this.savingsDepositAmount=savingsDepositAmount;
this.savingProductType=savingProductType;
this.tenureType=tenureType;
this.tenure=tenure;
this.frequency=frequency;
this.interestType=interestType;
this.interestCalculationMethod=interestCalculationMethod;
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal;
this.isPartialDepositAllowed=isPartialDepositAllowed;
this.isLockinPeriodAllowed=isLockinPeriodAllowed;
this.lockinPeriod=lockinPeriod;
this.lockinPeriodType=lockinPeriodType;
}
public MonetaryCurrency getCurrency() { @Embedded
return this.currency.copy(); private MonetaryCurrency currency;
}
public BigDecimal getInterestRate() { @Column(name = "interest_rate", scale = 6, precision = 19, nullable = false)
return BigDecimal.valueOf(Double.valueOf(this.interestRate.stripTrailingZeros().toString())); private BigDecimal interestRate;
}
public BigDecimal getMinimumBalance(){
return BigDecimal.valueOf(Double.valueOf(this.savingsDepositAmount.stripTrailingZeros().toString()));
}
public void update(SavingProductCommand command){
Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal();
if (command.isDigitsAfterDecimalChanged()) {
digitsAfterDecimal = command.getDigitsAfterDecimal();
}
String currencyCodeChanged = this.currency.getCode();
if (command.isCurrencyCodeChanged()) {
currencyCodeChanged = command.getCurrencyCode();
}
if (command.isDigitsAfterDecimalChanged() || command.isCurrencyCodeChanged()) {
this.currency = new MonetaryCurrency(currencyCodeChanged, digitsAfterDecimal);
}
if (command.isInterestRateChanged()) {
this.interestRate = command.getInterestRate();
}
if(command.isSavingsDepositAmountChanged()){
this.savingsDepositAmount=command.getSavingsDepositAmount();
}
if (command.isSavingProductTypeChanged()) {
this.savingProductType=SavingProductType.fromInt(command.getSavingProductType());
}
if(command.isTenureTypeChanged()){
this.tenureType=TenureTypeEnum.fromInt(command.getTenureType());
}
if (command.isTenureChanged()) {
this.tenure = command.getTenure();
}
if (command.isFrequencyChanged()){
this.frequency = SavingFrequencyType.fromInt(command.getFrequency());
}
if (command.isInterestTypeChanged()) {
this.interestType = SavingsInterestType.fromInt(command.getInterestType());
}
if (command.isInterestCalculationMethodChanged()){
this.interestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
}
if (command.isMinimumBalanceForWithdrawalChanged()) {
this.minimumBalanceForWithdrawal = command.getMinimumBalanceForWithdrawal();
}
if (command.isPartialDepositAllowedChanged()) {
this.isPartialDepositAllowed = command.isPartialDepositAllowed();
}
if (command.isLockinPeriodAllowedChanged()){
this.isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
if (command.isLockinPeriodChanged()){
this.lockinPeriod = command.getLockinPeriod();
}
if (command.isLockinPeriodTypeChanged()){
this.lockinPeriodType=PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
}
public BigDecimal getSavingsDepositAmount() { @SuppressWarnings("unused")
return savingsDepositAmount; @Column(name = "min_interest_rate", scale = 6, precision = 19, nullable = false)
} private BigDecimal minInterestRate;
public SavingProductType getSavingProductType() { @SuppressWarnings("unused")
return savingProductType; @Column(name = "max_interest_rate", scale = 6, precision = 19, nullable = false)
} private BigDecimal maxInterestRate;
public TenureTypeEnum getTenureType() { @Column(name = "savings_deposit_amount", scale = 6, precision = 19, nullable = false)
return tenureType; private BigDecimal savingsDepositAmount;
}
public Integer getTenure() { @Column(name = "savings_product_type", nullable = false)
return tenure; private SavingProductType savingProductType;
}
public SavingFrequencyType getFrequency() { @Column(name = "tenure_type", nullable = false)
return frequency; private TenureTypeEnum tenureType;
}
public SavingsInterestType getInterestType() { @Column(name = "tenure", nullable = false)
return interestType; private Integer tenure;
}
public SavingInterestCalculationMethod getInterestCalculationMethod() { @Column(name = "frequency", nullable = false)
return interestCalculationMethod; private SavingFrequencyType frequency;
}
public BigDecimal getMinimumBalanceForWithdrawal() { @Column(name = "interest_type", nullable = false)
return minimumBalanceForWithdrawal; private SavingsInterestType interestType;
}
public boolean isPartialDepositAllowed() { @Column(name = "interest_calculation_method")
return isPartialDepositAllowed; private SavingInterestCalculationMethod interestCalculationMethod;
}
public boolean isLockinPeriodAllowed() { @Column(name = "min_bal_for_withdrawal", scale = 6, precision = 19, nullable = false)
return isLockinPeriodAllowed; private BigDecimal minimumBalanceForWithdrawal;
}
public Integer getLockinPeriod() { @Column(name = "is_partial_deposit_allowed", nullable = false)
return lockinPeriod; private boolean isPartialDepositAllowed;
}
@Column(name = "is_lock_in_period_allowed", nullable = false)
private boolean isLockinPeriodAllowed;
@Column(name = "lock_in_period", nullable = false)
private Integer lockinPeriod;
@Column(name = "lock_in_period_type", nullable = false)
private PeriodFrequencyType lockinPeriodType;
public SavingProductRelatedDetail() {
this.interestRate = null;
this.savingsDepositAmount = null;
}
public SavingProductRelatedDetail(final MonetaryCurrency currency, final BigDecimal interestRate, final BigDecimal minInterestRate,
final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount, final SavingProductType savingProductType,
final TenureTypeEnum tenureType, final Integer tenure, final SavingFrequencyType frequency,
final SavingsInterestType interestType, final SavingInterestCalculationMethod interestCalculationMethod,
final BigDecimal minimumBalanceForWithdrawal, final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed,
final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType) {
this.currency = currency;
this.interestRate = interestRate;
this.minInterestRate = minInterestRate;
this.maxInterestRate = maxInterestRate;
this.savingsDepositAmount = savingsDepositAmount;
this.savingProductType = savingProductType;
this.tenureType = tenureType;
this.tenure = tenure;
this.frequency = frequency;
this.interestType = interestType;
this.interestCalculationMethod = interestCalculationMethod;
this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.isPartialDepositAllowed = isPartialDepositAllowed;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
}
public MonetaryCurrency getCurrency() {
return this.currency.copy();
}
public BigDecimal getInterestRate() {
return BigDecimal.valueOf(Double.valueOf(this.interestRate.stripTrailingZeros().toString()));
}
public BigDecimal getMinimumBalance() {
return BigDecimal.valueOf(Double.valueOf(this.savingsDepositAmount.stripTrailingZeros().toString()));
}
public void update(SavingProductCommand command) {
Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal();
if (command.isDigitsAfterDecimalChanged()) {
digitsAfterDecimal = command.getDigitsAfterDecimal();
}
String currencyCodeChanged = this.currency.getCode();
if (command.isCurrencyCodeChanged()) {
currencyCodeChanged = command.getCurrencyCode();
}
if (command.isDigitsAfterDecimalChanged() || command.isCurrencyCodeChanged()) {
this.currency = new MonetaryCurrency(currencyCodeChanged, digitsAfterDecimal);
}
if (command.isInterestRateChanged()) {
this.interestRate = command.getInterestRate();
}
if (command.isSavingsDepositAmountChanged()) {
this.savingsDepositAmount = command.getSavingsDepositAmount();
}
if (command.isSavingProductTypeChanged()) {
this.savingProductType = SavingProductType.fromInt(command.getSavingProductType());
}
if (command.isTenureTypeChanged()) {
this.tenureType = TenureTypeEnum.fromInt(command.getTenureType());
}
if (command.isTenureChanged()) {
this.tenure = command.getTenure();
}
if (command.isFrequencyChanged()) {
this.frequency = SavingFrequencyType.fromInt(command.getFrequency());
}
if (command.isInterestTypeChanged()) {
this.interestType = SavingsInterestType.fromInt(command.getInterestType());
}
if (command.isInterestCalculationMethodChanged()) {
this.interestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
}
if (command.isMinimumBalanceForWithdrawalChanged()) {
this.minimumBalanceForWithdrawal = command.getMinimumBalanceForWithdrawal();
}
if (command.isPartialDepositAllowedChanged()) {
this.isPartialDepositAllowed = command.isPartialDepositAllowed();
}
if (command.isLockinPeriodAllowedChanged()) {
this.isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
if (command.isLockinPeriodChanged()) {
this.lockinPeriod = command.getLockinPeriod();
}
if (command.isLockinPeriodTypeChanged()) {
this.lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
}
public BigDecimal getSavingsDepositAmount() {
return savingsDepositAmount;
}
public SavingProductType getSavingProductType() {
return savingProductType;
}
public TenureTypeEnum getTenureType() {
return tenureType;
}
public Integer getTenure() {
return tenure;
}
public SavingFrequencyType getFrequency() {
return frequency;
}
public SavingsInterestType getInterestType() {
return interestType;
}
public SavingInterestCalculationMethod getInterestCalculationMethod() {
return interestCalculationMethod;
}
public BigDecimal getMinimumBalanceForWithdrawal() {
return minimumBalanceForWithdrawal;
}
public boolean isPartialDepositAllowed() {
return isPartialDepositAllowed;
}
public boolean isLockinPeriodAllowed() {
return isLockinPeriodAllowed;
}
public Integer getLockinPeriod() {
return lockinPeriod;
}
public PeriodFrequencyType getLockinPeriodType() {
return lockinPeriodType;
}
public PeriodFrequencyType getLockinPeriodType() {
return lockinPeriodType;
}
} }
@@ -3,8 +3,6 @@ package org.mifosplatform.portfolio.savingsaccountproduct.domain;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface SavingProductRepository extends public interface SavingProductRepository extends JpaRepository<SavingProduct, Long>, JpaSpecificationExecutor<SavingProduct> {
JpaRepository<SavingProduct, Long>, //
JpaSpecificationExecutor<SavingProduct> { }
}
@@ -1,50 +1,48 @@
package org.mifosplatform.portfolio.savingsaccountproduct.domain; package org.mifosplatform.portfolio.savingsaccountproduct.domain;
public enum SavingProductType { public enum SavingProductType {
INVALID(0,"savingProductType.invalid"),
RECCURING(1,"savingProductType.reccuring"),
REGULAR(2,"savingProductType.regular");
private final Integer value;
private final String code;
private SavingProductType(final Integer value,final String code) {
this.value=value;
this.code=code;
}
public Integer getValue() {
return value;
}
public String getCode() {
return code;
}
public static SavingProductType fromInt(final Integer frequency) {
SavingProductType savingProductType = SavingProductType.INVALID; INVALID(0, "savingProductType.invalid"), RECCURING(1, "savingProductType.reccuring"), REGULAR(2, "savingProductType.regular");
switch (frequency) {
case 1: private final Integer value;
savingProductType = SavingProductType.RECCURING; private final String code;
break;
case 2: private SavingProductType(final Integer value, final String code) {
savingProductType = SavingProductType.REGULAR; this.value = value;
break; this.code = code;
default: }
savingProductType = SavingProductType.INVALID;
break; public Integer getValue() {
} return value;
return savingProductType; }
}
public String getCode() {
public boolean isReccuring(){ return code;
return this.value.equals(SavingProductType.RECCURING.getValue()); }
}
public static SavingProductType fromInt(final Integer frequency) {
public boolean isRegular(){
return this.value.equals(SavingProductType.REGULAR.getValue()); SavingProductType savingProductType = SavingProductType.INVALID;
} switch (frequency) {
case 1:
savingProductType = SavingProductType.RECCURING;
break;
case 2:
savingProductType = SavingProductType.REGULAR;
break;
default:
savingProductType = SavingProductType.INVALID;
break;
}
return savingProductType;
}
public boolean isReccuring() {
return this.value.equals(SavingProductType.RECCURING.getValue());
}
public boolean isRegular() {
return this.value.equals(SavingProductType.REGULAR.getValue());
}
} }
@@ -1,42 +1,40 @@
package org.mifosplatform.portfolio.savingsaccountproduct.domain; package org.mifosplatform.portfolio.savingsaccountproduct.domain;
public enum SavingsInterestType { public enum SavingsInterestType {
INVALID(0,"savingsInterestType.invalid"),
SIMPLE(1,"savingsInterestType.simple"),
COMPOUNDING(2,"savingsInterestType.compounding");
private final Integer value;
private final String code;
private SavingsInterestType(final Integer value,final String code) {
this.value=value;
this.code=code;
}
public Integer getValue() {
return value;
}
public String getCode() {
return code;
}
public static SavingsInterestType fromInt(final Integer frequency) {
SavingsInterestType savingsInterestType = SavingsInterestType.INVALID; INVALID(0, "savingsInterestType.invalid"), SIMPLE(1, "savingsInterestType.simple"), COMPOUNDING(2, "savingsInterestType.compounding");
switch (frequency) {
case 1: private final Integer value;
savingsInterestType = SavingsInterestType.SIMPLE; private final String code;
break;
case 2: private SavingsInterestType(final Integer value, final String code) {
savingsInterestType = SavingsInterestType.COMPOUNDING; this.value = value;
break; this.code = code;
default: }
savingsInterestType = SavingsInterestType.INVALID;
break; public Integer getValue() {
} return value;
return savingsInterestType; }
}
public String getCode() {
return code;
}
public static SavingsInterestType fromInt(final Integer frequency) {
SavingsInterestType savingsInterestType = SavingsInterestType.INVALID;
switch (frequency) {
case 1:
savingsInterestType = SavingsInterestType.SIMPLE;
break;
case 2:
savingsInterestType = SavingsInterestType.COMPOUNDING;
break;
default:
savingsInterestType = SavingsInterestType.INVALID;
break;
}
return savingsInterestType;
}
} }
@@ -1,52 +1,50 @@
package org.mifosplatform.portfolio.savingsaccountproduct.domain; package org.mifosplatform.portfolio.savingsaccountproduct.domain;
public enum SavingsLockinPeriodEnum { public enum SavingsLockinPeriodEnum {
DAYS(0, "lockin.period.type.days"), // DAYS(0, "lockin.period.type.days"), //
WEEKS(1, "lockin.period.type.weeks"), // WEEKS(1, "lockin.period.type.weeks"), //
MONTHS(2, "lockin.period.type.months"), // MONTHS(2, "lockin.period.type.months"), //
YEARS(3, "lockin.period.type.years"), // YEARS(3, "lockin.period.type.years"), //
INVALID(4, "lockin.period.type.invalid"); INVALID(4, "lockin.period.type.invalid");
private final Integer value; private final Integer value;
private final String code; private final String code;
private SavingsLockinPeriodEnum(final Integer value, final String code) { private SavingsLockinPeriodEnum(final Integer value, final String code) {
this.value = value; this.value = value;
this.code = code; this.code = code;
} }
public Integer getValue() { public Integer getValue() {
return this.value; return this.value;
} }
public String getCode() {
return code;
}
public static SavingsLockinPeriodEnum fromInt(final Integer frequency) {
SavingsLockinPeriodEnum lockinPeriodType = SavingsLockinPeriodEnum.INVALID; public String getCode() {
switch (frequency) { return code;
case 0: }
lockinPeriodType = SavingsLockinPeriodEnum.DAYS;
break;
case 1:
lockinPeriodType = SavingsLockinPeriodEnum.WEEKS;
break;
case 2:
lockinPeriodType = SavingsLockinPeriodEnum.MONTHS;
break;
case 3:
lockinPeriodType = SavingsLockinPeriodEnum.YEARS;
break;
default:
lockinPeriodType = SavingsLockinPeriodEnum.INVALID;
break;
}
return lockinPeriodType;
}
public static SavingsLockinPeriodEnum fromInt(final Integer frequency) {
SavingsLockinPeriodEnum lockinPeriodType = SavingsLockinPeriodEnum.INVALID;
switch (frequency) {
case 0:
lockinPeriodType = SavingsLockinPeriodEnum.DAYS;
break;
case 1:
lockinPeriodType = SavingsLockinPeriodEnum.WEEKS;
break;
case 2:
lockinPeriodType = SavingsLockinPeriodEnum.MONTHS;
break;
case 3:
lockinPeriodType = SavingsLockinPeriodEnum.YEARS;
break;
default:
lockinPeriodType = SavingsLockinPeriodEnum.INVALID;
break;
}
return lockinPeriodType;
}
} }
@@ -2,11 +2,9 @@ package org.mifosplatform.portfolio.savingsaccountproduct.exception;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException;
public class SavingProductNotFoundException extends public class SavingProductNotFoundException extends AbstractPlatformResourceNotFoundException {
AbstractPlatformResourceNotFoundException {
public SavingProductNotFoundException(Long id) { public SavingProductNotFoundException(Long id) {
super("error.msg.savingproduct.id.invalid", "Saving product with identifier " + id + " does not exist", id); super("error.msg.savingproduct.id.invalid", "Saving product with identifier " + id + " does not exist", id);
} }
}
}
@@ -9,77 +9,89 @@ import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidation
import org.mifosplatform.portfolio.savingsaccountproduct.command.SavingProductCommand; import org.mifosplatform.portfolio.savingsaccountproduct.command.SavingProductCommand;
public class SavingProductCommandValidator { public class SavingProductCommandValidator {
private final SavingProductCommand command;
public SavingProductCommandValidator(final SavingProductCommand command) {
this.command=command;
}
public void validateForUpdate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsproduct"); private final SavingProductCommand command;
baseDataValidator.reset().parameter("id").value(command.getId()).notNull();
baseDataValidator.reset().parameter("name").value(command.getName()).ignoreIfNull().notBlank(); public SavingProductCommandValidator(final SavingProductCommand command) {
baseDataValidator.reset().parameter("description").value(command.getDescription()).ignoreIfNull().notExceedingLengthOf(500); this.command = command;
baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).ignoreIfNull().notBlank(); }
baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).ignoreIfNull().inMinMaxRange(0, 6);
baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).ignoreIfNull().notBlank(); public void validateForUpdate() {
baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).ignoreIfNull().notBlank(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("interestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate()); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsproduct");
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate()); baseDataValidator.reset().parameter("id").value(command.getId()).notNull();
baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).ignoreIfNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("name").value(command.getName()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).ignoreIfNull(); baseDataValidator.reset().parameter("description").value(command.getDescription()).ignoreIfNull().notExceedingLengthOf(500);
baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).ignoreIfNull(); baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("tenure").value(command.getTenure()).ignoreIfNull(); baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).ignoreIfNull().inMinMaxRange(0, 6);
baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).ignoreIfNull(); baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).ignoreIfNull(); baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).ignoreIfNull(); baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).ignoreIfNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("minInterestRate")
baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed()).trueOrFalseRequired(command.isPartialDepositAllowedChanged()).ignoreIfNull(); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed()).trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).ignoreIfNull(); baseDataValidator.reset().parameter("interestRate")
baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).ignoreIfNull(); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).ignoreIfNull(); baseDataValidator.reset().parameter("minInterestRate")
.comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate());
if (!dataValidationErrors.isEmpty()) { baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).ignoreIfNull()
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); .zeroOrPositiveAmount();
} baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).ignoreIfNull();
} baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).ignoreIfNull();
baseDataValidator.reset().parameter("tenure").value(command.getTenure()).ignoreIfNull();
public void validateForCreate() { baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).ignoreIfNull();
baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).ignoreIfNull();
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).ignoreIfNull();
baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).ignoreIfNull()
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("product"); .zeroOrPositiveAmount();
baseDataValidator.reset().parameter("name").value(command.getName()).notBlank(); baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed())
baseDataValidator.reset().parameter("description").value(command.getDescription()).notExceedingLengthOf(500); .trueOrFalseRequired(command.isPartialDepositAllowedChanged()).ignoreIfNull();
baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).notBlank(); baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed())
baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).notNull().inMinMaxRange(0, 6); .trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).ignoreIfNull();
baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).ignoreIfNull();
baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).ignoreIfNull();
baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate()); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
baseDataValidator.reset().parameter("interestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate()); "Validation errors exist.", dataValidationErrors); }
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate()); }
baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).notNull(); public void validateForCreate() {
baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).notNull();
baseDataValidator.reset().parameter("tenure").value(command.getTenure()).notNull(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).notNull();
baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).notNull(); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("product");
baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).notNull(); baseDataValidator.reset().parameter("name").value(command.getName()).notBlank();
baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("description").value(command.getDescription()).notExceedingLengthOf(500);
baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed()).trueOrFalseRequired(command.isPartialDepositAllowedChanged()).notNull(); baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).notBlank();
baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed()).trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).notNull(); baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).notNull().inMinMaxRange(0, 6);
baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).notNull(); baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).notNull(); baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).notNull().zeroOrPositiveAmount();
if (!dataValidationErrors.isEmpty()) { baseDataValidator.reset().parameter("minInterestRate")
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate());
} baseDataValidator.reset().parameter("interestRate")
} .comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("minInterestRate")
.comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate());
baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).notNull()
.zeroOrPositiveAmount();
baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).notNull();
baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).notNull();
baseDataValidator.reset().parameter("tenure").value(command.getTenure()).notNull();
baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).notNull();
baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).notNull();
baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).notNull();
baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).notNull()
.zeroOrPositiveAmount();
baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed())
.trueOrFalseRequired(command.isPartialDepositAllowedChanged()).notNull();
baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed())
.trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).notNull();
baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).notNull();
baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).notNull();
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); }
}
} }
@@ -9,155 +9,181 @@ import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsLockinPer
import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum;
public class SavingProductEnumerations { public class SavingProductEnumerations {
public static EnumOptionData savingProductType(final int id) {
return savingProductType(SavingProductType.fromInt(id));
}
public static EnumOptionData tenureTypeEnum(final int id) {
return tenureTypeEnum(TenureTypeEnum.fromInt(id));
}
public static EnumOptionData interestFrequencyType(final int id) {
return interestFrequencyType(SavingFrequencyType.fromInt(id));
}
public static EnumOptionData savingInterestType(final int id) {
return savingInterestType(SavingsInterestType.fromInt(id));
}
public static EnumOptionData savingInterestCalculationMethod(final int id) {
return savingInterestCalculationMethod(SavingInterestCalculationMethod.fromInt(id));
}
public static EnumOptionData savingsLockinPeriod(final int id){
return savingsLockinPeriod(SavingsLockinPeriodEnum.fromInt(id));
}
public static EnumOptionData savingsLockinPeriod(SavingsLockinPeriodEnum type) {
final String codePrefix = "savings.product.";
EnumOptionData optionData = null;
switch (type) {
case DAYS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.DAYS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.DAYS.getCode(), "Days");
break;
case MONTHS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.MONTHS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.MONTHS.getCode(), "Months");
break;
case WEEKS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.WEEKS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.WEEKS.getCode(), "Weeks");
break;
case YEARS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.YEARS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.YEARS.getCode(), "Years");
break;
default:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.INVALID.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData savingInterestCalculationMethod(SavingInterestCalculationMethod type) { public static EnumOptionData savingProductType(final int id) {
final String codePrefix = "savings.interestCalculation.method."; return savingProductType(SavingProductType.fromInt(id));
EnumOptionData optionData = null; }
switch (type) {
case MINBAL:
optionData = new EnumOptionData(SavingInterestCalculationMethod.MINBAL.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.MINBAL.getCode(), "Minimumbalance");
break;
case AVERAGEBAL:
optionData = new EnumOptionData(SavingInterestCalculationMethod.AVERAGEBAL.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.AVERAGEBAL.getCode(), "AverageBalance");
break;
case INVALID:
optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.INVALID.getCode(), "Invalid");
break;
case MONTHLYCOLLECTION:
optionData = new EnumOptionData(SavingInterestCalculationMethod.MONTHLYCOLLECTION.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.MONTHLYCOLLECTION.getCode(), "MonthlyCollection");
break;
default:
optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData savingInterestType(SavingsInterestType type) { public static EnumOptionData tenureTypeEnum(final int id) {
final String codePrefix = "savings.interest.type."; return tenureTypeEnum(TenureTypeEnum.fromInt(id));
EnumOptionData optionData = null; }
switch (type) {
case COMPOUNDING:
optionData = new EnumOptionData(SavingsInterestType.COMPOUNDING.getValue().longValue(), codePrefix+SavingsInterestType.COMPOUNDING.getCode(), "Compounding");
break;
case SIMPLE:
optionData = new EnumOptionData(SavingsInterestType.SIMPLE.getValue().longValue(), codePrefix+SavingsInterestType.SIMPLE.getCode(), "Simple");
break;
default:
optionData = new EnumOptionData(SavingsInterestType.INVALID.getValue().longValue(), codePrefix+SavingsInterestType.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData interestFrequencyType(SavingFrequencyType type) { public static EnumOptionData interestFrequencyType(final int id) {
final String codePrefix = "saving.product.frequency.period."; return interestFrequencyType(SavingFrequencyType.fromInt(id));
EnumOptionData optionData = null; }
switch (type) {
case DAILY:
optionData = new EnumOptionData(SavingFrequencyType.DAILY.getValue().longValue(), codePrefix + SavingFrequencyType.DAILY.getCode(), "Days");
break;
case MONTHLY:
optionData = new EnumOptionData(SavingFrequencyType.MONTHLY.getValue().longValue(), codePrefix + SavingFrequencyType.MONTHLY.getCode(), "Weeks");
break;
case QUATERLY:
optionData = new EnumOptionData(SavingFrequencyType.QUATERLY.getValue().longValue(), codePrefix + SavingFrequencyType.QUATERLY.getCode(), "Months");
break;
case HALFYEARLY:
optionData = new EnumOptionData(SavingFrequencyType.HALFYEARLY.getValue().longValue(), codePrefix + SavingFrequencyType.HALFYEARLY.getCode(), "Months");
break;
case YEARLY:
optionData = new EnumOptionData(SavingFrequencyType.YEARLY.getValue().longValue(), codePrefix + SavingFrequencyType.YEARLY.getCode(), "Yearly");
break;
default:
optionData = new EnumOptionData(SavingFrequencyType.INVALID.getValue().longValue(), SavingFrequencyType.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData tenureTypeEnum(final TenureTypeEnum type) { public static EnumOptionData savingInterestType(final int id) {
final String codePrefix = "savings.tenure."; return savingInterestType(SavingsInterestType.fromInt(id));
EnumOptionData optionData = null; }
switch (type) {
case FIXED_PERIOD:
optionData = new EnumOptionData(TenureTypeEnum.FIXED_PERIOD.getValue().longValue(), codePrefix+TenureTypeEnum.FIXED_PERIOD.getCode(), "FixedPeriod");
break;
case PERPETUAL:
optionData = new EnumOptionData(TenureTypeEnum.PERPETUAL.getValue().longValue(), codePrefix+TenureTypeEnum.PERPETUAL.getCode(), "Perpetual");
break;
default:
optionData = new EnumOptionData(TenureTypeEnum.INVALID.getValue().longValue(), codePrefix+TenureTypeEnum.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData savingProductType(final SavingProductType type) { public static EnumOptionData savingInterestCalculationMethod(final int id) {
final String codePrefix = "savings.product."; return savingInterestCalculationMethod(SavingInterestCalculationMethod.fromInt(id));
EnumOptionData optionData = null; }
switch (type) {
case RECCURING: public static EnumOptionData savingsLockinPeriod(final int id) {
optionData = new EnumOptionData(SavingProductType.RECCURING.getValue().longValue(), codePrefix + SavingProductType.RECCURING.getCode(), "Reccuring"); return savingsLockinPeriod(SavingsLockinPeriodEnum.fromInt(id));
break; }
case REGULAR:
optionData = new EnumOptionData(SavingProductType.REGULAR.getValue().longValue(), codePrefix + SavingProductType.REGULAR.getCode(), "Regular"); public static EnumOptionData savingsLockinPeriod(SavingsLockinPeriodEnum type) {
break; final String codePrefix = "savings.product.";
case INVALID: EnumOptionData optionData = null;
optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), codePrefix + SavingProductType.INVALID.getCode(), "Invalid"); switch (type) {
break; case DAYS:
default: optionData = new EnumOptionData(SavingsLockinPeriodEnum.DAYS.getValue().longValue(), codePrefix
optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), SavingProductType.INVALID.getCode(), "Invalid"); + SavingsLockinPeriodEnum.DAYS.getCode(), "Days");
break; break;
} case MONTHS:
return optionData; optionData = new EnumOptionData(SavingsLockinPeriodEnum.MONTHS.getValue().longValue(), codePrefix
} + SavingsLockinPeriodEnum.MONTHS.getCode(), "Months");
break;
case WEEKS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.WEEKS.getValue().longValue(), codePrefix
+ SavingsLockinPeriodEnum.WEEKS.getCode(), "Weeks");
break;
case YEARS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.YEARS.getValue().longValue(), codePrefix
+ SavingsLockinPeriodEnum.YEARS.getCode(), "Years");
break;
default:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.INVALID.getValue().longValue(), codePrefix
+ SavingsLockinPeriodEnum.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData savingInterestCalculationMethod(SavingInterestCalculationMethod type) {
final String codePrefix = "savings.interestCalculation.method.";
EnumOptionData optionData = null;
switch (type) {
case MINBAL:
optionData = new EnumOptionData(SavingInterestCalculationMethod.MINBAL.getValue().longValue(), codePrefix
+ SavingInterestCalculationMethod.MINBAL.getCode(), "Minimumbalance");
break;
case AVERAGEBAL:
optionData = new EnumOptionData(SavingInterestCalculationMethod.AVERAGEBAL.getValue().longValue(), codePrefix
+ SavingInterestCalculationMethod.AVERAGEBAL.getCode(), "AverageBalance");
break;
case INVALID:
optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix
+ SavingInterestCalculationMethod.INVALID.getCode(), "Invalid");
break;
case MONTHLYCOLLECTION:
optionData = new EnumOptionData(SavingInterestCalculationMethod.MONTHLYCOLLECTION.getValue().longValue(), codePrefix
+ SavingInterestCalculationMethod.MONTHLYCOLLECTION.getCode(), "MonthlyCollection");
break;
default:
optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix
+ SavingInterestCalculationMethod.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData savingInterestType(SavingsInterestType type) {
final String codePrefix = "savings.interest.type.";
EnumOptionData optionData = null;
switch (type) {
case COMPOUNDING:
optionData = new EnumOptionData(SavingsInterestType.COMPOUNDING.getValue().longValue(), codePrefix
+ SavingsInterestType.COMPOUNDING.getCode(), "Compounding");
break;
case SIMPLE:
optionData = new EnumOptionData(SavingsInterestType.SIMPLE.getValue().longValue(), codePrefix
+ SavingsInterestType.SIMPLE.getCode(), "Simple");
break;
default:
optionData = new EnumOptionData(SavingsInterestType.INVALID.getValue().longValue(), codePrefix
+ SavingsInterestType.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData interestFrequencyType(SavingFrequencyType type) {
final String codePrefix = "saving.product.frequency.period.";
EnumOptionData optionData = null;
switch (type) {
case DAILY:
optionData = new EnumOptionData(SavingFrequencyType.DAILY.getValue().longValue(), codePrefix
+ SavingFrequencyType.DAILY.getCode(), "Days");
break;
case MONTHLY:
optionData = new EnumOptionData(SavingFrequencyType.MONTHLY.getValue().longValue(), codePrefix
+ SavingFrequencyType.MONTHLY.getCode(), "Weeks");
break;
case QUATERLY:
optionData = new EnumOptionData(SavingFrequencyType.QUATERLY.getValue().longValue(), codePrefix
+ SavingFrequencyType.QUATERLY.getCode(), "Months");
break;
case HALFYEARLY:
optionData = new EnumOptionData(SavingFrequencyType.HALFYEARLY.getValue().longValue(), codePrefix
+ SavingFrequencyType.HALFYEARLY.getCode(), "Months");
break;
case YEARLY:
optionData = new EnumOptionData(SavingFrequencyType.YEARLY.getValue().longValue(), codePrefix
+ SavingFrequencyType.YEARLY.getCode(), "Yearly");
break;
default:
optionData = new EnumOptionData(SavingFrequencyType.INVALID.getValue().longValue(), SavingFrequencyType.INVALID.getCode(),
"Invalid");
break;
}
return optionData;
}
public static EnumOptionData tenureTypeEnum(final TenureTypeEnum type) {
final String codePrefix = "savings.tenure.";
EnumOptionData optionData = null;
switch (type) {
case FIXED_PERIOD:
optionData = new EnumOptionData(TenureTypeEnum.FIXED_PERIOD.getValue().longValue(), codePrefix
+ TenureTypeEnum.FIXED_PERIOD.getCode(), "FixedPeriod");
break;
case PERPETUAL:
optionData = new EnumOptionData(TenureTypeEnum.PERPETUAL.getValue().longValue(), codePrefix
+ TenureTypeEnum.PERPETUAL.getCode(), "Perpetual");
break;
default:
optionData = new EnumOptionData(TenureTypeEnum.INVALID.getValue().longValue(), codePrefix
+ TenureTypeEnum.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
public static EnumOptionData savingProductType(final SavingProductType type) {
final String codePrefix = "savings.product.";
EnumOptionData optionData = null;
switch (type) {
case RECCURING:
optionData = new EnumOptionData(SavingProductType.RECCURING.getValue().longValue(), codePrefix
+ SavingProductType.RECCURING.getCode(), "Reccuring");
break;
case REGULAR:
optionData = new EnumOptionData(SavingProductType.REGULAR.getValue().longValue(), codePrefix
+ SavingProductType.REGULAR.getCode(), "Regular");
break;
case INVALID:
optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), codePrefix
+ SavingProductType.INVALID.getCode(), "Invalid");
break;
default:
optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), SavingProductType.INVALID.getCode(),
"Invalid");
break;
}
return optionData;
}
} }
@@ -7,11 +7,11 @@ import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductLooku
public interface SavingProductReadPlatformService { public interface SavingProductReadPlatformService {
Collection<SavingProductData> retrieveAllSavingProducts(); Collection<SavingProductData> retrieveAllSavingProducts();
Collection<SavingProductLookup> retrieveAllSavingProductsForLookup(); Collection<SavingProductLookup> retrieveAllSavingProductsForLookup();
SavingProductData retrieveSavingProduct(Long productId); SavingProductData retrieveSavingProduct(Long productId);
SavingProductData retrieveNewSavingProductDetails(); SavingProductData retrieveNewSavingProductDetails();
} }
@@ -25,150 +25,151 @@ import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class SavingProductReadPlatformServiceImpl implements public class SavingProductReadPlatformServiceImpl implements SavingProductReadPlatformService {
SavingProductReadPlatformService {
private final PlatformSecurityContext context;
private final JdbcTemplate jdbcTemplate;
private final CurrencyReadPlatformService currencyReadPlatformService;
@Autowired
public SavingProductReadPlatformServiceImpl(final PlatformSecurityContext context,final TenantAwareRoutingDataSource dataSource,final CurrencyReadPlatformService currencyReadPlatformService) {
this.context=context;
jdbcTemplate=new JdbcTemplate(dataSource);
this.currencyReadPlatformService=currencyReadPlatformService;
}
@Override private final PlatformSecurityContext context;
public Collection<SavingProductData> retrieveAllSavingProducts() { private final JdbcTemplate jdbcTemplate;
private final CurrencyReadPlatformService currencyReadPlatformService;
this.context.authenticatedUser();
SavingProductMapper savingProductMapper=new SavingProductMapper();
String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.is_deleted=0";
return this.jdbcTemplate.query(sql,savingProductMapper, new Object[]{});
}
@Override @Autowired
public Collection<SavingProductLookup> retrieveAllSavingProductsForLookup() { public SavingProductReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final CurrencyReadPlatformService currencyReadPlatformService) {
this.context.authenticatedUser();
SavingProductLookupMapper savingProductLookupMapper=new SavingProductLookupMapper();
String sql="select"+savingProductLookupMapper.savingProductLookupSchema();
return this.jdbcTemplate.query(sql, savingProductLookupMapper, new Object[]{});
}
@Override this.context = context;
public SavingProductData retrieveSavingProduct(Long savingProductId) { jdbcTemplate = new JdbcTemplate(dataSource);
try{ this.currencyReadPlatformService = currencyReadPlatformService;
this.context.authenticatedUser(); }
SavingProductMapper savingProductMapper=new SavingProductMapper();
String sql = "select " + savingProductMapper.savingProductSchema()
+ " where sp.id = ? and sp.is_deleted=0";
SavingProductData productData = this.jdbcTemplate.queryForObject(sql,
savingProductMapper, new Object[] { savingProductId });
populateProductDataWithDropdownOptions(productData);
return productData; @Override
} catch (EmptyResultDataAccessException e) { public Collection<SavingProductData> retrieveAllSavingProducts() {
throw new LoanProductNotFoundException(savingProductId);
}
}
@Override this.context.authenticatedUser();
public SavingProductData retrieveNewSavingProductDetails() {
SavingProductData productData=new SavingProductData();
populateProductDataWithDropdownOptions(productData);
return productData;
}
private static final class SavingProductMapper implements RowMapper<SavingProductData> {
public String savingProductSchema(){
return "sp.id as id,sp.name as name, sp.description as description,sp.currency_code as currencyCode, sp.currency_digits as currencyDigits,sp.interest_rate as interestRate, "
+ "sp.min_interest_rate as minInterestRate, sp.max_interest_rate as maxInterstRate, "
+ " sp.savings_deposit_amount as savingsDepositAmount, sp.savings_product_type as savingProductType, sp.tenure_type as tenureType, sp.tenure as tenure, sp.frequency as frequency, "
+ " sp.interest_type as interestType, sp.interest_calculation_method as interestCalculationMethod, sp.min_bal_for_withdrawal as minimumBalanceForWithdrawal, "
+ " sp.is_partial_deposit_allowed as isPartialDepositAllowed, sp.is_lock_in_period_allowed as isLockinPeriodAllowed, sp.lock_in_period as lockinPeriod, sp.lock_in_period_type as lockinPeriodType, "
+ " sp.created_date as createdon, sp.lastmodified_date as modifiedon, "
+ "curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol"
+ " from m_product_savings sp join m_currency curr on curr.code = sp.currency_code";
}
@Override SavingProductMapper savingProductMapper = new SavingProductMapper();
public SavingProductData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum)
throws SQLException {
Long id = rs.getLong("id");
String name = rs.getString("name");
String description = rs.getString("description");
String currencyCode = rs.getString("currencyCode");
String currencyName = rs.getString("currencyName");
String currencyNameCode = rs.getString("currencyNameCode");
String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
Integer currencyDigits = JdbcSupport.getInteger(rs,"currencyDigits");
CurrencyData currencyData = new CurrencyData(currencyCode,currencyName, currencyDigits, currencyDisplaySymbol,currencyNameCode);
BigDecimal interestRate = rs.getBigDecimal("interestRate");
BigDecimal minInterestRate = rs.getBigDecimal("minInterestRate");
BigDecimal maxInterestRate = rs.getBigDecimal("maxInterstRate");
DateTime createdOn = JdbcSupport.getDateTime(rs, "createdon");
DateTime lastModifedOn = JdbcSupport.getDateTime(rs, "modifiedon");
BigDecimal savingsDepositAmount=rs.getBigDecimal("savingsDepositAmount");
EnumOptionData savingProductTypeEnum=SavingProductEnumerations.savingProductType(SavingProductType.fromInt(JdbcSupport.getInteger(rs, "savingProductType")));
EnumOptionData tenureTypeEnum = SavingProductEnumerations.tenureTypeEnum(JdbcSupport.getInteger(rs, "tenureType"));
Integer tenure = JdbcSupport.getInteger(rs, "tenure");
EnumOptionData savingFrequencyType = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, "frequency"));
EnumOptionData savingInterestType = SavingProductEnumerations.savingInterestType(JdbcSupport.getInteger(rs, "interestType"));
EnumOptionData interestCalculationMethodEnum=SavingProductEnumerations.savingInterestCalculationMethod(JdbcSupport.getInteger(rs, "interestCalculationMethod"));
BigDecimal minimumBalanceForWithdrawal=rs.getBigDecimal("minimumBalanceForWithdrawal");
boolean isPartialDepositAllowed = rs.getBoolean("isPartialDepositAllowed");
boolean isLockinPeriodAllowed =rs.getBoolean("isLockinPeriodAllowed");
Integer lockinPeriod=JdbcSupport.getInteger(rs, "lockinPeriod");
EnumOptionData lockinPeriodType= SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType.fromInt(JdbcSupport.getInteger(rs, "lockinPeriodType")));
return new SavingProductData(createdOn, lastModifedOn, id, name, description, interestRate, minInterestRate, maxInterestRate, currencyData, currencyDigits, savingsDepositAmount,
savingProductTypeEnum, tenureTypeEnum, tenure, savingFrequencyType, savingInterestType, interestCalculationMethodEnum,
minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType);
}
}
private static final class SavingProductLookupMapper implements
RowMapper<SavingProductLookup> {
public String savingProductLookupSchema() { String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.is_deleted=0";
return "sp.id as id, sp.name as name from m_product_savings sp";
}
@Override return this.jdbcTemplate.query(sql, savingProductMapper, new Object[] {});
public SavingProductLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
Long id = rs.getLong("id"); }
String name = rs.getString("name");
return new SavingProductLookup(id, name); @Override
} public Collection<SavingProductLookup> retrieveAllSavingProductsForLookup() {
} this.context.authenticatedUser();
private void populateProductDataWithDropdownOptions(final SavingProductData productData) {
List<CurrencyData> currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies(); SavingProductLookupMapper savingProductLookupMapper = new SavingProductLookupMapper();
productData.setCurrencyOptions(currencyOptions);
} String sql = "select" + savingProductLookupMapper.savingProductLookupSchema();
return this.jdbcTemplate.query(sql, savingProductLookupMapper, new Object[] {});
}
@Override
public SavingProductData retrieveSavingProduct(Long savingProductId) {
try {
this.context.authenticatedUser();
SavingProductMapper savingProductMapper = new SavingProductMapper();
String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.id = ? and sp.is_deleted=0";
SavingProductData productData = this.jdbcTemplate.queryForObject(sql, savingProductMapper, new Object[] { savingProductId });
populateProductDataWithDropdownOptions(productData);
return productData;
} catch (EmptyResultDataAccessException e) {
throw new LoanProductNotFoundException(savingProductId);
}
}
@Override
public SavingProductData retrieveNewSavingProductDetails() {
SavingProductData productData = new SavingProductData();
populateProductDataWithDropdownOptions(productData);
return productData;
}
private static final class SavingProductMapper implements RowMapper<SavingProductData> {
public String savingProductSchema() {
return "sp.id as id,sp.name as name, sp.description as description,sp.currency_code as currencyCode, sp.currency_digits as currencyDigits,sp.interest_rate as interestRate, "
+ "sp.min_interest_rate as minInterestRate, sp.max_interest_rate as maxInterstRate, "
+ " sp.savings_deposit_amount as savingsDepositAmount, sp.savings_product_type as savingProductType, sp.tenure_type as tenureType, sp.tenure as tenure, sp.frequency as frequency, "
+ " sp.interest_type as interestType, sp.interest_calculation_method as interestCalculationMethod, sp.min_bal_for_withdrawal as minimumBalanceForWithdrawal, "
+ " sp.is_partial_deposit_allowed as isPartialDepositAllowed, sp.is_lock_in_period_allowed as isLockinPeriodAllowed, sp.lock_in_period as lockinPeriod, sp.lock_in_period_type as lockinPeriodType, "
+ " sp.created_date as createdon, sp.lastmodified_date as modifiedon, "
+ "curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol"
+ " from m_product_savings sp join m_currency curr on curr.code = sp.currency_code";
}
@Override
public SavingProductData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException {
Long id = rs.getLong("id");
String name = rs.getString("name");
String description = rs.getString("description");
String currencyCode = rs.getString("currencyCode");
String currencyName = rs.getString("currencyName");
String currencyNameCode = rs.getString("currencyNameCode");
String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode);
BigDecimal interestRate = rs.getBigDecimal("interestRate");
BigDecimal minInterestRate = rs.getBigDecimal("minInterestRate");
BigDecimal maxInterestRate = rs.getBigDecimal("maxInterstRate");
DateTime createdOn = JdbcSupport.getDateTime(rs, "createdon");
DateTime lastModifedOn = JdbcSupport.getDateTime(rs, "modifiedon");
BigDecimal savingsDepositAmount = rs.getBigDecimal("savingsDepositAmount");
EnumOptionData savingProductTypeEnum = SavingProductEnumerations.savingProductType(SavingProductType.fromInt(JdbcSupport
.getInteger(rs, "savingProductType")));
EnumOptionData tenureTypeEnum = SavingProductEnumerations.tenureTypeEnum(JdbcSupport.getInteger(rs, "tenureType"));
Integer tenure = JdbcSupport.getInteger(rs, "tenure");
EnumOptionData savingFrequencyType = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, "frequency"));
EnumOptionData savingInterestType = SavingProductEnumerations.savingInterestType(JdbcSupport.getInteger(rs, "interestType"));
EnumOptionData interestCalculationMethodEnum = SavingProductEnumerations.savingInterestCalculationMethod(JdbcSupport
.getInteger(rs, "interestCalculationMethod"));
BigDecimal minimumBalanceForWithdrawal = rs.getBigDecimal("minimumBalanceForWithdrawal");
boolean isPartialDepositAllowed = rs.getBoolean("isPartialDepositAllowed");
boolean isLockinPeriodAllowed = rs.getBoolean("isLockinPeriodAllowed");
Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod");
EnumOptionData lockinPeriodType = SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType
.fromInt(JdbcSupport.getInteger(rs, "lockinPeriodType")));
return new SavingProductData(createdOn, lastModifedOn, id, name, description, interestRate, minInterestRate, maxInterestRate,
currencyData, currencyDigits, savingsDepositAmount, savingProductTypeEnum, tenureTypeEnum, tenure, savingFrequencyType,
savingInterestType, interestCalculationMethodEnum, minimumBalanceForWithdrawal, isPartialDepositAllowed,
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType);
}
}
private static final class SavingProductLookupMapper implements RowMapper<SavingProductLookup> {
public String savingProductLookupSchema() {
return "sp.id as id, sp.name as name from m_product_savings sp";
}
@Override
public SavingProductLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id");
String name = rs.getString("name");
return new SavingProductLookup(id, name);
}
}
private void populateProductDataWithDropdownOptions(final SavingProductData productData) {
List<CurrencyData> currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies();
productData.setCurrencyOptions(currencyOptions);
}
} }
@@ -6,12 +6,12 @@ import org.springframework.security.access.prepost.PreAuthorize;
public interface SavingProductWritePlatformService { public interface SavingProductWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'CREATE_SAVINGSPRODUCT')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'CREATE_SAVINGSPRODUCT')")
EntityIdentifier createSavingProduct(SavingProductCommand command); EntityIdentifier createSavingProduct(SavingProductCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'UPDATE_SAVINGSPRODUCT')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'UPDATE_SAVINGSPRODUCT')")
EntityIdentifier updateSavingProduct(SavingProductCommand command); EntityIdentifier updateSavingProduct(SavingProductCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'DELETE_SAVINGSPRODUCT')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'DELETE_SAVINGSPRODUCT')")
EntityIdentifier deleteSavingProduct(Long productId); EntityIdentifier deleteSavingProduct(Long productId);
} }
@@ -21,70 +21,68 @@ import org.springframework.transaction.annotation.Transactional;
@Service @Service
public class SavingProductWritePlatformServiceJpaRepositoryImpl implements SavingProductWritePlatformService { public class SavingProductWritePlatformServiceJpaRepositoryImpl implements SavingProductWritePlatformService {
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final SavingProductRepository savingProductRepository; private final SavingProductRepository savingProductRepository;
@Autowired
public SavingProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final SavingProductRepository savingProductRepository) {
this.context=context;
this.savingProductRepository=savingProductRepository;
}
@Transactional
@Override
public EntityIdentifier createSavingProduct(final SavingProductCommand command) {
this.context.authenticatedUser();
SavingProductCommandValidator validator=new SavingProductCommandValidator(command);
validator.validateForCreate();
SavingProductType savingProductType = SavingProductType.fromInt(command.getSavingProductType());
TenureTypeEnum tenureType = TenureTypeEnum.fromInt(command.getTenureType());
SavingFrequencyType savingFrequencyType=SavingFrequencyType.fromInt(command.getFrequency());
SavingsInterestType interestType = SavingsInterestType.fromInt(command.getInterestType());
PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
SavingInterestCalculationMethod savingInterestCalculationMethod=SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
MonetaryCurrency currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
SavingProduct product = new SavingProduct(command.getName(), command.getDescription(), currency, command.getInterestRate(), command.getMinInterestRate(), command.getMaxInterestRate(),
command.getSavingsDepositAmount(), savingProductType, tenureType, command.getTenure(), savingFrequencyType, interestType,
savingInterestCalculationMethod, command.getMinimumBalanceForWithdrawal(), command.isPartialDepositAllowed(),
command.isLockinPeriodAllowed(), command.getLockinPeriod(), lockinPeriodType);
this.savingProductRepository.save(product);
return new EntityIdentifier(product.getId());
}
@Transactional @Autowired
@Override public SavingProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context,
public EntityIdentifier updateSavingProduct(final SavingProductCommand command) { final SavingProductRepository savingProductRepository) {
this.context = context;
this.context.authenticatedUser(); this.savingProductRepository = savingProductRepository;
SavingProductCommandValidator validator=new SavingProductCommandValidator(command); }
validator.validateForUpdate();
@Transactional
SavingProduct product=this.savingProductRepository.findOne(command.getId()); @Override
if (product == null) { public EntityIdentifier createSavingProduct(final SavingProductCommand command) {
throw new SavingProductNotFoundException(command.getId());
} this.context.authenticatedUser();
product.update(command); SavingProductCommandValidator validator = new SavingProductCommandValidator(command);
this.savingProductRepository.save(product); validator.validateForCreate();
return new EntityIdentifier(Long.valueOf(product.getId()));
} SavingProductType savingProductType = SavingProductType.fromInt(command.getSavingProductType());
TenureTypeEnum tenureType = TenureTypeEnum.fromInt(command.getTenureType());
SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
SavingsInterestType interestType = SavingsInterestType.fromInt(command.getInterestType());
PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command
.getInterestCalculationMethod());
MonetaryCurrency currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
SavingProduct product = new SavingProduct(command.getName(), command.getDescription(), currency, command.getInterestRate(),
command.getMinInterestRate(), command.getMaxInterestRate(), command.getSavingsDepositAmount(), savingProductType,
tenureType, command.getTenure(), savingFrequencyType, interestType, savingInterestCalculationMethod,
command.getMinimumBalanceForWithdrawal(), command.isPartialDepositAllowed(), command.isLockinPeriodAllowed(),
command.getLockinPeriod(), lockinPeriodType);
this.savingProductRepository.save(product);
return new EntityIdentifier(product.getId());
}
@Transactional
@Override
public EntityIdentifier updateSavingProduct(final SavingProductCommand command) {
this.context.authenticatedUser();
SavingProductCommandValidator validator = new SavingProductCommandValidator(command);
validator.validateForUpdate();
SavingProduct product = this.savingProductRepository.findOne(command.getId());
if (product == null) { throw new SavingProductNotFoundException(command.getId()); }
product.update(command);
this.savingProductRepository.save(product);
return new EntityIdentifier(Long.valueOf(product.getId()));
}
@Transactional
@Override
public EntityIdentifier deleteSavingProduct(Long productId) {
this.context.authenticatedUser();
SavingProduct product = this.savingProductRepository.findOne(productId);
if (product == null || product.isDeleted()) { throw new SavingsProductNotFoundException(productId); }
product.delete();
this.savingProductRepository.save(product);
return new EntityIdentifier(Long.valueOf(product.getId()));
}
@Transactional
@Override
public EntityIdentifier deleteSavingProduct(Long productId) {
this.context.authenticatedUser();
SavingProduct product=this.savingProductRepository.findOne(productId);
if (product==null || product.isDeleted()) {
throw new SavingsProductNotFoundException(productId);
}
product.delete();
this.savingProductRepository.save(product);
return new EntityIdentifier(Long.valueOf(product.getId()));
}
} }
@@ -4,28 +4,32 @@ import org.mifosplatform.infrastructure.core.data.EnumOptionData;
import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType;
public class SavingsDepositEnumerations { public class SavingsDepositEnumerations {
public static EnumOptionData interestCompoundingPeriodType(final int id) { public static EnumOptionData interestCompoundingPeriodType(final int id) {
return interestCompoundingPeriodType(PeriodFrequencyType.fromInt(id)); return interestCompoundingPeriodType(PeriodFrequencyType.fromInt(id));
} }
public static EnumOptionData interestCompoundingPeriodType(final PeriodFrequencyType type) { public static EnumOptionData interestCompoundingPeriodType(final PeriodFrequencyType type) {
final String codePrefix = "deposit.interest.compounding.period."; final String codePrefix = "deposit.interest.compounding.period.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case DAYS: case DAYS:
optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix + PeriodFrequencyType.DAYS.getCode(), "Days"); optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix
break; + PeriodFrequencyType.DAYS.getCode(), "Days");
case WEEKS: break;
optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix + PeriodFrequencyType.WEEKS.getCode(), "Weeks"); case WEEKS:
break; optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix
case MONTHS: + PeriodFrequencyType.WEEKS.getCode(), "Weeks");
optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix + PeriodFrequencyType.MONTHS.getCode(), "Months"); break;
break; case MONTHS:
default: optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix
optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), "Invalid"); + PeriodFrequencyType.MONTHS.getCode(), "Months");
break; break;
} default:
return optionData; optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(),
} "Invalid");
break;
}
return optionData;
}
} }
@@ -258,16 +258,16 @@ public class DepositAccountsApiResource {
private boolean is(final String commandParam, final String commandValue) { private boolean is(final String commandParam, final String commandValue) {
return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue);
} }
@POST
@Path("postinterest") @POST
@Consumes({ MediaType.APPLICATION_JSON }) @Path("postinterest")
@Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
public Response postInterest(){ @Produces({ MediaType.APPLICATION_JSON })
Collection<DepositAccountsForLookup> accounts = this.depositAccountReadPlatformService.retrieveDepositAccountForLookup(); public Response postInterest() {
@SuppressWarnings("unused") Collection<DepositAccountsForLookup> accounts = this.depositAccountReadPlatformService.retrieveDepositAccountForLookup();
EntityIdentifier entityIdentifier = this.depositAccountWritePlatformService.postInterestToDepositAccount(accounts); EntityIdentifier entityIdentifier = this.depositAccountWritePlatformService.postInterestToDepositAccount(accounts);
return Response.ok().entity(entityIdentifier).build(); return Response.ok().entity(entityIdentifier).build();
} }
} }
@@ -65,11 +65,11 @@ public class DepositAccountData {
private final boolean isLockinPeriodAllowed; private final boolean isLockinPeriodAllowed;
private final Integer lockinPeriod; private final Integer lockinPeriod;
private final EnumOptionData lockinPeriodType; private final EnumOptionData lockinPeriodType;
private final BigDecimal availableInterest; private final BigDecimal availableInterest;
private final BigDecimal interestPostedAmount; private final BigDecimal interestPostedAmount;
private final LocalDate lastInterestPostedDate; private final LocalDate lastInterestPostedDate;
private final LocalDate nextInterestPostedDate; private final LocalDate nextInterestPostedDate;
/* /*
* used when returning account template data but only a clientId is passed, * used when returning account template data but only a clientId is passed,
@@ -124,11 +124,11 @@ public class DepositAccountData {
this.isLockinPeriodAllowed = true; this.isLockinPeriodAllowed = true;
this.lockinPeriod = null; this.lockinPeriod = null;
this.lockinPeriodType = null; this.lockinPeriodType = null;
this.availableInterest = BigDecimal.ZERO; this.availableInterest = BigDecimal.ZERO;
this.interestPostedAmount = BigDecimal.ZERO; this.interestPostedAmount = BigDecimal.ZERO;
this.lastInterestPostedDate = null; this.lastInterestPostedDate = null;
this.nextInterestPostedDate = null; this.nextInterestPostedDate = null;
} }
public DepositAccountData(final DepositAccountData account, final List<EnumOptionData> interestCompoundedEveryPeriodTypeOptions, public DepositAccountData(final DepositAccountData account, final List<EnumOptionData> interestCompoundedEveryPeriodTypeOptions,
@@ -176,11 +176,11 @@ public class DepositAccountData {
this.lockinPeriod = account.getLockinPeriod(); this.lockinPeriod = account.getLockinPeriod();
this.lockinPeriodType = account.getLockinPeriodType(); this.lockinPeriodType = account.getLockinPeriodType();
this.isLockinPeriodAllowed = account.isLockinPeriodAllowed(); this.isLockinPeriodAllowed = account.isLockinPeriodAllowed();
this.availableInterest = account.getAvailableInterest(); this.availableInterest = account.getAvailableInterest();
this.interestPostedAmount = account.getInterestPostedAmount(); this.interestPostedAmount = account.getInterestPostedAmount();
this.lastInterestPostedDate = account.getLastInterestPostedDate(); this.lastInterestPostedDate = account.getLastInterestPostedDate();
this.nextInterestPostedDate = account.getNextInterestPostedDate(); this.nextInterestPostedDate = account.getNextInterestPostedDate();
} }
public DepositAccountData(final DepositAccountData account, final DepositPermissionData permissions, public DepositAccountData(final DepositAccountData account, final DepositPermissionData permissions,
@@ -228,11 +228,11 @@ public class DepositAccountData {
this.lockinPeriod = account.getLockinPeriod(); this.lockinPeriod = account.getLockinPeriod();
this.lockinPeriodType = account.getLockinPeriodType(); this.lockinPeriodType = account.getLockinPeriodType();
this.isLockinPeriodAllowed = account.isLockinPeriodAllowed(); this.isLockinPeriodAllowed = account.isLockinPeriodAllowed();
this.availableInterest = account.getAvailableInterest(); this.availableInterest = account.getAvailableInterest();
this.interestPostedAmount = account.getInterestPostedAmount(); this.interestPostedAmount = account.getInterestPostedAmount();
this.lastInterestPostedDate = account.getLastInterestPostedDate(); this.lastInterestPostedDate = account.getLastInterestPostedDate();
this.nextInterestPostedDate = account.getNextInterestPostedDate(); this.nextInterestPostedDate = account.getNextInterestPostedDate();
} }
public DepositAccountData(final Long id, final String externalId, final EnumOptionData status, final Long clientId, public DepositAccountData(final Long id, final String externalId, final EnumOptionData status, final Long clientId,
@@ -244,7 +244,7 @@ public class DepositAccountData {
final boolean preClosureAllowed, final BigDecimal preClosureInterestRate, final LocalDate withdrawnonDate, final boolean preClosureAllowed, final BigDecimal preClosureInterestRate, final LocalDate withdrawnonDate,
final LocalDate rejectedonDate, final LocalDate closedonDate, final boolean isInterestWithdrawable, final LocalDate rejectedonDate, final LocalDate closedonDate, final boolean isInterestWithdrawable,
final BigDecimal interestPaid, final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed, final BigDecimal interestPaid, final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed,
final Integer lockinPeriod, final EnumOptionData lockinPeriodType,final BigDecimal availableInterest, final Integer lockinPeriod, final EnumOptionData lockinPeriodType, final BigDecimal availableInterest,
final BigDecimal interestPostedAmount, final LocalDate lastInterestPostedDate, final LocalDate nextInterestPostedDate) { final BigDecimal interestPostedAmount, final LocalDate lastInterestPostedDate, final LocalDate nextInterestPostedDate) {
this.id = id; this.id = id;
this.externalId = externalId; this.externalId = externalId;
@@ -290,11 +290,11 @@ public class DepositAccountData {
this.isLockinPeriodAllowed = isLockinPeriodAllowed; this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod; this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType; this.lockinPeriodType = lockinPeriodType;
this.availableInterest = availableInterest; this.availableInterest = availableInterest;
this.interestPostedAmount = interestPostedAmount; this.interestPostedAmount = interestPostedAmount;
this.lastInterestPostedDate = lastInterestPostedDate; this.lastInterestPostedDate = lastInterestPostedDate;
this.nextInterestPostedDate = nextInterestPostedDate; this.nextInterestPostedDate = nextInterestPostedDate;
} }
public DepositAccountData(final Long clientId, final String clientName, final Long productId, final String productName, public DepositAccountData(final Long clientId, final String clientName, final Long productId, final String productName,
@@ -345,11 +345,11 @@ public class DepositAccountData {
this.lockinPeriod = Integer.valueOf(0); this.lockinPeriod = Integer.valueOf(0);
this.isLockinPeriodAllowed = true; this.isLockinPeriodAllowed = true;
this.lockinPeriodType = interestCompoundedEveryPeriodType; this.lockinPeriodType = interestCompoundedEveryPeriodType;
this.availableInterest = BigDecimal.ZERO; this.availableInterest = BigDecimal.ZERO;
this.interestPostedAmount = BigDecimal.ZERO; this.interestPostedAmount = BigDecimal.ZERO;
this.lastInterestPostedDate = null; this.lastInterestPostedDate = null;
this.nextInterestPostedDate = null; this.nextInterestPostedDate = null;
} }
public Long getId() { public Long getId() {
@@ -509,66 +509,77 @@ public class DepositAccountData {
} }
public BigDecimal getAvailableInterest() { public BigDecimal getAvailableInterest() {
return this.availableInterest; return this.availableInterest;
} }
public BigDecimal getInterestPostedAmount() { public BigDecimal getInterestPostedAmount() {
return this.interestPostedAmount; return this.interestPostedAmount;
} }
public LocalDate getLastInterestPostedDate() { public LocalDate getLastInterestPostedDate() {
return this.lastInterestPostedDate; return this.lastInterestPostedDate;
} }
public LocalDate getNextInterestPostedDate() { public LocalDate getNextInterestPostedDate() {
return this.nextInterestPostedDate; return this.nextInterestPostedDate;
} }
private BigDecimal determineAvailableInterestForWithdrawal(final DepositAccountData account) {
BigDecimal availableInterestForWithdrawal = BigDecimal.ZERO;
if(this.status!=null){
if (account.getStatus().getId() == 300) {
BigDecimal interestGettingForPeriod = BigDecimal.valueOf(account.getActualInterestAccrued().doubleValue()/ new Double(account.getTenureInMonths()));
LocalDate interestWithdrawingDate= new LocalDate().isBefore(getMaturedOn())?new LocalDate():getMaturedOn().plusDays(1);
Integer noOfMonthsforInterestCal = Months.monthsBetween(account.getActualCommencementDate(), interestWithdrawingDate).getMonths();
Integer noOfPeriods = noOfMonthsforInterestCal/ account.getInterestCompoundedEvery();
availableInterestForWithdrawal = BigDecimal.valueOf(interestGettingForPeriod.multiply(new BigDecimal(noOfPeriods)).doubleValue()- account.getInterestPaid().doubleValue()); private BigDecimal determineAvailableInterestForWithdrawal(final DepositAccountData account) {
}else { BigDecimal availableInterestForWithdrawal = BigDecimal.ZERO;
return BigDecimal.ZERO;
}
}else return BigDecimal.ZERO;
return availableInterestForWithdrawal;
}
private BigDecimal determineAvalableWithdrawalAmount(final DepositAccountData account) {
BigDecimal avalablePreclosureWithdrawalAmount = BigDecimal.ZERO;
if(this.status != null){
if (account.getStatus().getId() == 300) {
// if(new LocalDate().isBefore(account.getMaturedOn()) || new LocalDate().isEqual(account.getMaturedOn())){
Integer days = Days.daysBetween(account.getLastInterestPostedDate(), new LocalDate()).getDays();
avalablePreclosureWithdrawalAmount=account.getAvailableInterest().add(account.getDeposit()).add(determineRemainInerestAmount(account.getDeposit(), account.getPreClosureInterestRate(), days));
// }else if(new LocalDate().isAfter(account.getMaturedOn())){
// Integer days = Days.daysBetween(account.getLastInterestPostedDate(), new LocalDate()).getDays();
// avalablePreclosureWithdrawalAmount=account.getAvailableInterest().add(account.getDeposit()).add(determineRemainInerestAmount(account.getDeposit(), account.getPreClosureInterestRate(), days));
// }
}else{
avalablePreclosureWithdrawalAmount=account.getDeposit();
}
}
return avalablePreclosureWithdrawalAmount;
}
private BigDecimal determineRemainInerestAmount(final BigDecimal depsoitAmount, final BigDecimal interstRateApplicable, final Integer days){
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); if (this.status != null) {
Integer daysInYear = 365; if (account.getStatus().getId() == 300) {
BigDecimal interestRateAsFraction = interstRateApplicable.divide(BigDecimal.valueOf(100), mc); BigDecimal interestGettingForPeriod = BigDecimal.valueOf(account.getActualInterestAccrued().doubleValue()
BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc); / new Double(account.getTenureInMonths()));
return BigDecimal.valueOf(depsoitAmount.doubleValue()*days.doubleValue()*interestRateForOneDay.doubleValue()); LocalDate interestWithdrawingDate = new LocalDate().isBefore(getMaturedOn()) ? new LocalDate() : getMaturedOn().plusDays(1);
Integer noOfMonthsforInterestCal = Months.monthsBetween(account.getActualCommencementDate(), interestWithdrawingDate)
} .getMonths();
Integer noOfPeriods = noOfMonthsforInterestCal / account.getInterestCompoundedEvery();
availableInterestForWithdrawal = BigDecimal.valueOf(interestGettingForPeriod.multiply(new BigDecimal(noOfPeriods))
.doubleValue() - account.getInterestPaid().doubleValue());
} else {
return BigDecimal.ZERO;
}
} else
return BigDecimal.ZERO;
return availableInterestForWithdrawal;
}
private BigDecimal determineAvalableWithdrawalAmount(final DepositAccountData account) {
BigDecimal avalablePreclosureWithdrawalAmount = BigDecimal.ZERO;
if (this.status != null) {
if (account.getStatus().getId() == 300) {
// if(new LocalDate().isBefore(account.getMaturedOn()) || new
// LocalDate().isEqual(account.getMaturedOn())){
Integer days = Days.daysBetween(account.getLastInterestPostedDate(), new LocalDate()).getDays();
avalablePreclosureWithdrawalAmount = account.getAvailableInterest().add(account.getDeposit())
.add(determineRemainInerestAmount(account.getDeposit(), account.getPreClosureInterestRate(), days));
// }else if(new LocalDate().isAfter(account.getMaturedOn())){
// Integer days =
// Days.daysBetween(account.getLastInterestPostedDate(), new
// LocalDate()).getDays();
// avalablePreclosureWithdrawalAmount=account.getAvailableInterest().add(account.getDeposit()).add(determineRemainInerestAmount(account.getDeposit(),
// account.getPreClosureInterestRate(), days));
// }
} else {
avalablePreclosureWithdrawalAmount = account.getDeposit();
}
}
return avalablePreclosureWithdrawalAmount;
}
private BigDecimal determineRemainInerestAmount(final BigDecimal depsoitAmount, final BigDecimal interstRateApplicable,
final Integer days) {
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer daysInYear = 365;
BigDecimal interestRateAsFraction = interstRateApplicable.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc);
return BigDecimal.valueOf(depsoitAmount.doubleValue() * days.doubleValue() * interestRateForOneDay.doubleValue());
}
} }
@@ -9,52 +9,51 @@ import org.mifosplatform.infrastructure.core.data.EnumOptionData;
* Immutable data object to represent transactions on a deposit account. * Immutable data object to represent transactions on a deposit account.
*/ */
public class DepositAccountTransactionData { public class DepositAccountTransactionData {
private final Long transactionId;
private final EnumOptionData transactionType;
private final LocalDate transactionDate;
private final BigDecimal transactionAmount;
private final Long accountId;
private final BigDecimal interestAmount;
private final BigDecimal total;
public DepositAccountTransactionData(
final Long transactionId, final Long accountId, final EnumOptionData transactionType,
final LocalDate transactionDate, final BigDecimal transactionAmount, final BigDecimal interstAmount, final BigDecimal total ) {
this.transactionId = transactionId;
this.accountId = accountId;
this.transactionType = transactionType;
this.transactionDate = transactionDate;
this.transactionAmount = transactionAmount;
this.interestAmount = interstAmount;
this.total = total;
}
public Long getAccountId() { private final Long transactionId;
return accountId; private final EnumOptionData transactionType;
} private final LocalDate transactionDate;
private final BigDecimal transactionAmount;
private final Long accountId;
private final BigDecimal interestAmount;
private final BigDecimal total;
public Long getTransactionId() { public DepositAccountTransactionData(final Long transactionId, final Long accountId, final EnumOptionData transactionType,
return transactionId; final LocalDate transactionDate, final BigDecimal transactionAmount, final BigDecimal interstAmount, final BigDecimal total) {
} this.transactionId = transactionId;
this.accountId = accountId;
this.transactionType = transactionType;
this.transactionDate = transactionDate;
this.transactionAmount = transactionAmount;
this.interestAmount = interstAmount;
this.total = total;
}
public EnumOptionData getTransactionType() { public Long getAccountId() {
return transactionType; return accountId;
} }
public LocalDate getTransactionDate() { public Long getTransactionId() {
return transactionDate; return transactionId;
} }
public BigDecimal getTransactionAmount() { public EnumOptionData getTransactionType() {
return transactionAmount; return transactionType;
} }
public BigDecimal getInterestAmount() { public LocalDate getTransactionDate() {
return interestAmount; return transactionDate;
} }
public BigDecimal getTotal() { public BigDecimal getTransactionAmount() {
return total; return transactionAmount;
} }
public BigDecimal getInterestAmount() {
return interestAmount;
}
public BigDecimal getTotal() {
return total;
}
} }
@@ -1,15 +1,15 @@
package org.mifosplatform.portfolio.savingsdepositaccount.data; package org.mifosplatform.portfolio.savingsdepositaccount.data;
public class DepositAccountsForLookup { public class DepositAccountsForLookup {
private final Long id;
public DepositAccountsForLookup(final Long id) {
this.id = id;
}
public Long getId() { private final Long id;
return id;
}
} public DepositAccountsForLookup(final Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
@@ -1,60 +1,60 @@
package org.mifosplatform.portfolio.savingsdepositaccount.data; package org.mifosplatform.portfolio.savingsdepositaccount.data;
public class DepositPermissionData { public class DepositPermissionData {
private final boolean rejectAllowed;
private final boolean withdrawnByApplicantAllowed;
private final boolean undoApprovalAllowed;
private final boolean pendingApproval;
private final boolean isInterestWithdrawalAllowed;
private final boolean renewelAllowed;
private final boolean isMaturedDepositAccount;
private final boolean anyActionOnAccountAllowed;
private final boolean rejectAllowed;
public DepositPermissionData(final boolean rejectAllowed,final boolean withdrawnByApplicantAllowed,final boolean undoApprovalAllowed, private final boolean withdrawnByApplicantAllowed;
final boolean pendingApproval,final boolean interestWithdrawalAllowed, final boolean renewelAllowed, final boolean isMaturedDepositAccount) { private final boolean undoApprovalAllowed;
this.rejectAllowed = rejectAllowed; private final boolean pendingApproval;
this.withdrawnByApplicantAllowed = withdrawnByApplicantAllowed; private final boolean isInterestWithdrawalAllowed;
this.undoApprovalAllowed = undoApprovalAllowed; private final boolean renewelAllowed;
this.pendingApproval = pendingApproval; private final boolean isMaturedDepositAccount;
this.isInterestWithdrawalAllowed = interestWithdrawalAllowed;
this.renewelAllowed = renewelAllowed;
this.isMaturedDepositAccount = isMaturedDepositAccount;
this.anyActionOnAccountAllowed = isRejectAllowed() || isPendingApproval() || isUndoApprovalAllowed() || isWithdrawnByApplicantAllowed() ||
isInterestWithdrawalAllowed() || isRenewelAllowed() || isMaturedDepositAccount();
}
public boolean isRejectAllowed() { private final boolean anyActionOnAccountAllowed;
return rejectAllowed;
}
public boolean isWithdrawnByApplicantAllowed() { public DepositPermissionData(final boolean rejectAllowed, final boolean withdrawnByApplicantAllowed, final boolean undoApprovalAllowed,
return withdrawnByApplicantAllowed; final boolean pendingApproval, final boolean interestWithdrawalAllowed, final boolean renewelAllowed,
} final boolean isMaturedDepositAccount) {
this.rejectAllowed = rejectAllowed;
this.withdrawnByApplicantAllowed = withdrawnByApplicantAllowed;
this.undoApprovalAllowed = undoApprovalAllowed;
this.pendingApproval = pendingApproval;
this.isInterestWithdrawalAllowed = interestWithdrawalAllowed;
this.renewelAllowed = renewelAllowed;
this.isMaturedDepositAccount = isMaturedDepositAccount;
this.anyActionOnAccountAllowed = isRejectAllowed() || isPendingApproval() || isUndoApprovalAllowed()
|| isWithdrawnByApplicantAllowed() || isInterestWithdrawalAllowed() || isRenewelAllowed() || isMaturedDepositAccount();
}
public boolean isUndoApprovalAllowed() { public boolean isRejectAllowed() {
return undoApprovalAllowed; return rejectAllowed;
} }
public boolean isPendingApproval() { public boolean isWithdrawnByApplicantAllowed() {
return pendingApproval; return withdrawnByApplicantAllowed;
} }
public boolean isAnyActionOnAccountAllowed() {
return anyActionOnAccountAllowed;
}
public boolean isInterestWithdrawalAllowed() { public boolean isUndoApprovalAllowed() {
return isInterestWithdrawalAllowed; return undoApprovalAllowed;
} }
public boolean isRenewelAllowed() { public boolean isPendingApproval() {
return renewelAllowed; return pendingApproval;
} }
public boolean isMaturedDepositAccount() { public boolean isAnyActionOnAccountAllowed() {
return isMaturedDepositAccount; return anyActionOnAccountAllowed;
} }
public boolean isInterestWithdrawalAllowed() {
return isInterestWithdrawalAllowed;
}
public boolean isRenewelAllowed() {
return renewelAllowed;
}
public boolean isMaturedDepositAccount() {
return isMaturedDepositAccount;
}
} }
@@ -1,7 +1,6 @@
package org.mifosplatform.portfolio.savingsdepositaccount.domain; package org.mifosplatform.portfolio.savingsdepositaccount.domain;
public enum DepositAccountEvent { public enum DepositAccountEvent {
DEPOSIT_CREATED, DEPOSIT_REJECTED, DEPOSIT_APPROVED, DEPOSIT_APPROVAL_UNDO, DEPOSIT_WITHDRAWN, DEPOSIT_MATURED, DEPOSIT_CLOSED, DEPOSIT_PRECLOSED;
} DEPOSIT_CREATED, DEPOSIT_REJECTED, DEPOSIT_APPROVED, DEPOSIT_APPROVAL_UNDO, DEPOSIT_WITHDRAWN, DEPOSIT_MATURED, DEPOSIT_CLOSED, DEPOSIT_PRECLOSED;
}
@@ -3,8 +3,6 @@ package org.mifosplatform.portfolio.savingsdepositaccount.domain;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface DepositAccountRepository extends public interface DepositAccountRepository extends JpaRepository<DepositAccount, Long>, JpaSpecificationExecutor<DepositAccount> {
JpaRepository<DepositAccount, Long>, //
JpaSpecificationExecutor<DepositAccount> { }
}
@@ -1,94 +1,94 @@
package org.mifosplatform.portfolio.savingsdepositaccount.domain; package org.mifosplatform.portfolio.savingsdepositaccount.domain;
public enum DepositAccountStatus { public enum DepositAccountStatus {
INVALID(0, "depositStatusType.invalid"), // INVALID(0, "depositStatusType.invalid"), //
SUBMITED_AND_PENDING_APPROVAL(100, "depositStatusType.submitted.and.pending.approval"), // SUBMITED_AND_PENDING_APPROVAL(100, "depositStatusType.submitted.and.pending.approval"), //
//APPROVED(200, "depositStatusType.approved"), // // APPROVED(200, "depositStatusType.approved"), //
ACTIVE(300, "depositStatusType.active"), // ACTIVE(300, "depositStatusType.active"), //
WITHDRAWN_BY_CLIENT(400, "depositStatusType.withdrawn.by.client"), // WITHDRAWN_BY_CLIENT(400, "depositStatusType.withdrawn.by.client"), //
REJECTED(500, "depositStatusType.rejected"), // REJECTED(500, "depositStatusType.rejected"), //
CLOSED(600, "depositStatusType.closed"), // CLOSED(600, "depositStatusType.closed"), //
MATURED(700,"depositStatusType.matured"), MATURED(700, "depositStatusType.matured"), PRECLOSED(800, "depositStatusType.preclosed");
PRECLOSED(800,"depositStatusType.preclosed");
private final Integer value; private final Integer value;
private final String code; private final String code;
private DepositAccountStatus(final Integer value, final String code) { private DepositAccountStatus(final Integer value, final String code) {
this.value = value; this.value = value;
this.code = code; this.code = code;
} }
public boolean hasStateOf(final DepositAccountStatus state) { public boolean hasStateOf(final DepositAccountStatus state) {
return this.value.equals(state.getValue()); return this.value.equals(state.getValue());
} }
public Integer getValue() { public Integer getValue() {
return value; return value;
} }
public String getCode() { public String getCode() {
return code; return code;
} }
public boolean isSubmittedAndPendingApproval() {
return this.value.equals(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue());
}
/*public boolean isApproved() {
return this.value.equals(DepositAccountStatus.APPROVED.getValue());
}*/
public boolean isActive() {
return this.value.equals(DepositAccountStatus.ACTIVE.getValue());
}
public boolean isClosed() { public boolean isSubmittedAndPendingApproval() {
return this.value.equals(DepositAccountStatus.CLOSED.getValue()); return this.value.equals(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue());
} }
public boolean isWithdrawnByClient() { /*
return this.value.equals(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue()); * public boolean isApproved() { return
} * this.value.equals(DepositAccountStatus.APPROVED.getValue()); }
*/
public boolean isRejected() { public boolean isActive() {
return this.value.equals(DepositAccountStatus.REJECTED.getValue()); return this.value.equals(DepositAccountStatus.ACTIVE.getValue());
} }
public boolean isPreClosed(){
return this.value.equals(DepositAccountStatus.PRECLOSED.getValue());
}
public static DepositAccountStatus fromInt(final Integer statusValue) {
DepositAccountStatus enumeration = DepositAccountStatus.INVALID; public boolean isClosed() {
switch (statusValue) { return this.value.equals(DepositAccountStatus.CLOSED.getValue());
case 100: }
enumeration = DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL;
break; public boolean isWithdrawnByClient() {
/*case 200: return this.value.equals(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue());
enumeration = DepositAccountStatus.APPROVED; }
break;*/
case 300: public boolean isRejected() {
enumeration = DepositAccountStatus.ACTIVE; return this.value.equals(DepositAccountStatus.REJECTED.getValue());
break; }
case 400:
enumeration = DepositAccountStatus.WITHDRAWN_BY_CLIENT; public boolean isPreClosed() {
break; return this.value.equals(DepositAccountStatus.PRECLOSED.getValue());
case 500: }
enumeration = DepositAccountStatus.REJECTED;
break; public static DepositAccountStatus fromInt(final Integer statusValue) {
case 600:
enumeration = DepositAccountStatus.CLOSED; DepositAccountStatus enumeration = DepositAccountStatus.INVALID;
break; switch (statusValue) {
case 700: case 100:
enumeration = DepositAccountStatus.MATURED; enumeration = DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL;
break; break;
case 800: /*
enumeration = DepositAccountStatus.PRECLOSED; * case 200: enumeration = DepositAccountStatus.APPROVED; break;
break; */
} case 300:
return enumeration; enumeration = DepositAccountStatus.ACTIVE;
} break;
case 400:
enumeration = DepositAccountStatus.WITHDRAWN_BY_CLIENT;
break;
case 500:
enumeration = DepositAccountStatus.REJECTED;
break;
case 600:
enumeration = DepositAccountStatus.CLOSED;
break;
case 700:
enumeration = DepositAccountStatus.MATURED;
break;
case 800:
enumeration = DepositAccountStatus.PRECLOSED;
break;
}
return enumeration;
}
} }
@@ -21,92 +21,97 @@ import org.mifosplatform.organisation.monetary.domain.Money;
import org.springframework.data.jpa.domain.AbstractPersistable; import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity @Entity
@Table(name="m_deposit_account_transaction") @Table(name = "m_deposit_account_transaction")
public class DepositAccountTransaction extends AbstractPersistable<Long> { public class DepositAccountTransaction extends AbstractPersistable<Long> {
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "deposit_account_id", nullable=false) @JoinColumn(name = "deposit_account_id", nullable = false)
private DepositAccount depositAccount; private DepositAccount depositAccount;
@Enumerated(EnumType.ORDINAL) @Enumerated(EnumType.ORDINAL)
@Column(name = "transaction_type_enum", nullable = false) @Column(name = "transaction_type_enum", nullable = false)
private DepositAccountTransactionType typeOf; private DepositAccountTransactionType typeOf;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@OneToOne(optional=true, cascade={CascadeType.PERSIST}) @OneToOne(optional = true, cascade = { CascadeType.PERSIST })
@JoinColumn(name="contra_id") @JoinColumn(name = "contra_id")
private DepositAccountTransaction contra; private DepositAccountTransaction contra;
@Temporal(TemporalType.DATE) @Temporal(TemporalType.DATE)
@Column(name = "transaction_date", nullable=false) @Column(name = "transaction_date", nullable = false)
private final Date dateOf; private final Date dateOf;
@Column(name = "amount", scale = 6, precision = 19, nullable = false) @Column(name = "amount", scale = 6, precision = 19, nullable = false)
private final BigDecimal amount; private final BigDecimal amount;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Column(name = "interest", scale = 6, precision = 19, nullable = false) @Column(name = "interest", scale = 6, precision = 19, nullable = false)
private final BigDecimal interest; private final BigDecimal interest;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Column(name = "total", scale = 6, precision = 19, nullable = false) @Column(name = "total", scale = 6, precision = 19, nullable = false)
private final BigDecimal total; private final BigDecimal total;
protected DepositAccountTransaction(){ protected DepositAccountTransaction() {
this.depositAccount=null; this.depositAccount = null;
this.typeOf=null; this.typeOf = null;
this.amount=null; this.amount = null;
this.dateOf=null; this.dateOf = null;
this.interest=null; this.interest = null;
this.total=null; this.total = null;
} }
private DepositAccountTransaction(DepositAccountTransactionType type, final BigDecimal amount, final LocalDate date, final BigDecimal interest) { private DepositAccountTransaction(DepositAccountTransactionType type, final BigDecimal amount, final LocalDate date,
this.typeOf = type; final BigDecimal interest) {
this.typeOf = type;
this.amount = amount; this.amount = amount;
this.dateOf = date.toDateMidnight().toDate(); this.dateOf = date.toDateMidnight().toDate();
this.interest = interest; this.interest = interest;
this.total = amount.doubleValue()==0?new BigDecimal(0):amount.add(interest); this.total = amount.doubleValue() == 0 ? new BigDecimal(0) : amount.add(interest);
} }
public Date getDateOf() { public Date getDateOf() {
return dateOf; return dateOf;
} }
public BigDecimal getAmount() { public BigDecimal getAmount() {
return amount; return amount;
} }
public DepositAccountTransactionType getTypeOf() {
return typeOf;
}
public Money getAmount(MonetaryCurrency currency) {
return Money.of(currency, this.amount);
}
public DepositAccountTransactionType getTypeOf() {
return typeOf;
}
public Money getAmount(MonetaryCurrency currency) {
return Money.of(currency, this.amount);
}
public LocalDate getTransactionDate() { public LocalDate getTransactionDate() {
return new LocalDate(this.dateOf); return new LocalDate(this.dateOf);
} }
public boolean isDeposit(){ public boolean isDeposit() {
return DepositAccountTransactionType.DEPOSIT.equals(typeOf); return DepositAccountTransactionType.DEPOSIT.equals(typeOf);
} }
public static DepositAccountTransaction deposit(Money amount, LocalDate paymentDate, Money interest) { public static DepositAccountTransaction deposit(Money amount, LocalDate paymentDate, Money interest) {
return new DepositAccountTransaction(DepositAccountTransactionType.DEPOSIT, amount == null ? new BigDecimal(0) : amount.getAmount(), paymentDate, interest==null ? new BigDecimal(0) : interest.getAmount()); return new DepositAccountTransaction(DepositAccountTransactionType.DEPOSIT,
} amount == null ? new BigDecimal(0) : amount.getAmount(), paymentDate, interest == null ? new BigDecimal(0)
: interest.getAmount());
public static DepositAccountTransaction withdraw(Money amount, LocalDate paymentDate, Money interest) { }
return new DepositAccountTransaction(DepositAccountTransactionType.WITHDRAW, amount == null ? new BigDecimal(0) : amount.getAmount(), paymentDate, interest==null ? new BigDecimal(0) : interest.getAmount());
} public static DepositAccountTransaction withdraw(Money amount, LocalDate paymentDate, Money interest) {
return new DepositAccountTransaction(DepositAccountTransactionType.WITHDRAW, amount == null ? new BigDecimal(0)
public static DepositAccountTransaction postInterest(Money depositAmount, LocalDate paymentDate, Money interest) { : amount.getAmount(), paymentDate, interest == null ? new BigDecimal(0) : interest.getAmount());
return new DepositAccountTransaction(DepositAccountTransactionType.INTEREST_POSTING, depositAmount == null ? new BigDecimal(0) : depositAmount.getAmount(), paymentDate, interest==null ? new BigDecimal(0) : interest.getAmount()); }
}
public static DepositAccountTransaction postInterest(Money depositAmount, LocalDate paymentDate, Money interest) {
public void updateAccount(DepositAccount depositAccount) { return new DepositAccountTransaction(DepositAccountTransactionType.INTEREST_POSTING, depositAmount == null ? new BigDecimal(0)
this.depositAccount=depositAccount; : depositAmount.getAmount(), paymentDate, interest == null ? new BigDecimal(0) : interest.getAmount());
} }
public void updateAccount(DepositAccount depositAccount) {
this.depositAccount = depositAccount;
}
} }
@@ -1,60 +1,57 @@
package org.mifosplatform.portfolio.savingsdepositaccount.domain; package org.mifosplatform.portfolio.savingsdepositaccount.domain;
public enum DepositAccountTransactionType { public enum DepositAccountTransactionType {
INVALID(0, "depositTransactionType.invalid"), // INVALID(0, "depositTransactionType.invalid"), //
DEPOSIT(1, "depositTransactionType.deposit"), // DEPOSIT(1, "depositTransactionType.deposit"), //
WITHDRAW(2, "depositTransactionType.withdraw"), // WITHDRAW(2, "depositTransactionType.withdraw"), //
REVERSAL(3, "depositTransactionType.reversal"), REVERSAL(3, "depositTransactionType.reversal"), INTEREST_POSTING(4, "depositTransactionType.interestPosting");
INTEREST_POSTING(4,"depositTransactionType.interestPosting");
private final Integer value; private final Integer value;
private final String code; private final String code;
private DepositAccountTransactionType(final Integer value, final String code) { private DepositAccountTransactionType(final Integer value, final String code) {
this.value=value; this.value = value;
this.code=code; this.code = code;
} }
public Integer getValue() { public Integer getValue() {
return value; return value;
} }
public String getCode() { public String getCode() {
return code; return code;
} }
public static DepositAccountTransactionType fromInt(final Integer transactionType){
if (transactionType == null) {
return DepositAccountTransactionType.INVALID;
}
DepositAccountTransactionType depositTransactionType=null;
switch (transactionType) {
case 1:
depositTransactionType=DepositAccountTransactionType.DEPOSIT;
break;
case 2:
depositTransactionType=DepositAccountTransactionType.WITHDRAW;
break;
case 3:
depositTransactionType=DepositAccountTransactionType.REVERSAL;
break;
case 4:
depositTransactionType=DepositAccountTransactionType.INTEREST_POSTING;
break;
default :
depositTransactionType=DepositAccountTransactionType.INVALID;
break;
} public static DepositAccountTransactionType fromInt(final Integer transactionType) {
return depositTransactionType; if (transactionType == null) { return DepositAccountTransactionType.INVALID; }
DepositAccountTransactionType depositTransactionType = null;
switch (transactionType) {
case 1:
depositTransactionType = DepositAccountTransactionType.DEPOSIT;
break;
case 2:
depositTransactionType = DepositAccountTransactionType.WITHDRAW;
break;
case 3:
depositTransactionType = DepositAccountTransactionType.REVERSAL;
break;
case 4:
depositTransactionType = DepositAccountTransactionType.INTEREST_POSTING;
break;
default:
depositTransactionType = DepositAccountTransactionType.INVALID;
break;
}
return depositTransactionType;
} }
} }
@@ -1,8 +1,6 @@
package org.mifosplatform.portfolio.savingsdepositaccount.domain; package org.mifosplatform.portfolio.savingsdepositaccount.domain;
public interface DepositLifecycleStateMachine { public interface DepositLifecycleStateMachine {
DepositAccountStatus transition(DepositAccountEvent loanEvent, DepositAccountStatus from);
} DepositAccountStatus transition(DepositAccountEvent loanEvent, DepositAccountStatus from);
}
@@ -4,119 +4,111 @@ import java.util.List;
import org.mifosplatform.portfolio.savingsdepositaccount.exception.InvalidDepositStateTransitionException; import org.mifosplatform.portfolio.savingsdepositaccount.exception.InvalidDepositStateTransitionException;
public class DepositLifecycleStateMachineImpl implements public class DepositLifecycleStateMachineImpl implements DepositLifecycleStateMachine {
DepositLifecycleStateMachine {
private final List<DepositAccountStatus> allowedDepositStatuses;
public DepositLifecycleStateMachineImpl(List<DepositAccountStatus> allowedDepositStatuses) {
this.allowedDepositStatuses=allowedDepositStatuses;
}
@Override private final List<DepositAccountStatus> allowedDepositStatuses;
public DepositAccountStatus transition(DepositAccountEvent depositEvent, DepositAccountStatus from) {
DepositAccountStatus newState = null;
switch (depositEvent) {
case DEPOSIT_CREATED:
if (from == null) {
newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses);
}
break;
case DEPOSIT_REJECTED:
if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) {
newState = stateOf(DepositAccountStatus.REJECTED, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be rejected from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("rejection", "failed", errorMessage,from);
}
break;
case DEPOSIT_APPROVED:
if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) {
newState = stateOf(DepositAccountStatus.ACTIVE, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be approved from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("approve", "failed", errorMessage,from);
}
break;
case DEPOSIT_WITHDRAWN:
if (this.anyOfAllowedWhenComingFrom(from, DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.WITHDRAWN_BY_CLIENT, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be withdrawn from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("withdrawbyclient", "failed", errorMessage,from);
}
break;
case DEPOSIT_APPROVAL_UNDO:
if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be unapproved from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("unapprove", "failed", errorMessage,from);
}
break;
case DEPOSIT_MATURED:
if (from.hasStateOf(DepositAccountStatus.ACTIVE) ){
newState = stateOf(DepositAccountStatus.MATURED, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be matured from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("mature", "failed", errorMessage,from);
}
break;
case DEPOSIT_CLOSED:
if (from.hasStateOf(DepositAccountStatus.ACTIVE) ){
newState = stateOf(DepositAccountStatus.CLOSED, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be closed from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("closed", "failed", errorMessage,from);
}
break;
case DEPOSIT_PRECLOSED:
if (from.hasStateOf(DepositAccountStatus.ACTIVE) ){
newState = stateOf(DepositAccountStatus.PRECLOSED, allowedDepositStatuses);
}
else{
final String errorMessage = "The DepositApplication can not be matured from "+from.getCode() ;
throw new InvalidDepositStateTransitionException("preclosure", "failed", errorMessage,from);
}
break;
default:
break;
}
return newState;
}
private DepositAccountStatus stateOf(DepositAccountStatus state, List<DepositAccountStatus> allowedLoanStatuses) {
DepositAccountStatus match = null;
for (DepositAccountStatus depositStatus : allowedLoanStatuses) {
if (depositStatus.hasStateOf(state)) {
match = depositStatus;
break;
}
}
return match;
}
private boolean anyOfAllowedWhenComingFrom(final DepositAccountStatus state, final DepositAccountStatus... allowedStates) { public DepositLifecycleStateMachineImpl(List<DepositAccountStatus> allowedDepositStatuses) {
boolean allowed = false; this.allowedDepositStatuses = allowedDepositStatuses;
}
for (DepositAccountStatus allowedState : allowedStates) { @Override
if (state.hasStateOf(allowedState)) { public DepositAccountStatus transition(DepositAccountEvent depositEvent, DepositAccountStatus from) {
allowed = true;
break;
}
}
return allowed; DepositAccountStatus newState = null;
}
switch (depositEvent) {
case DEPOSIT_CREATED:
if (from == null) {
newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses);
}
break;
case DEPOSIT_REJECTED:
if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) {
newState = stateOf(DepositAccountStatus.REJECTED, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be rejected from " + from.getCode();
throw new InvalidDepositStateTransitionException("rejection", "failed", errorMessage, from);
}
break;
case DEPOSIT_APPROVED:
if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) {
newState = stateOf(DepositAccountStatus.ACTIVE, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be approved from " + from.getCode();
throw new InvalidDepositStateTransitionException("approve", "failed", errorMessage, from);
}
break;
case DEPOSIT_WITHDRAWN:
if (this.anyOfAllowedWhenComingFrom(from, DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.WITHDRAWN_BY_CLIENT, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be withdrawn from " + from.getCode();
throw new InvalidDepositStateTransitionException("withdrawbyclient", "failed", errorMessage, from);
}
break;
case DEPOSIT_APPROVAL_UNDO:
if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be unapproved from " + from.getCode();
throw new InvalidDepositStateTransitionException("unapprove", "failed", errorMessage, from);
}
break;
case DEPOSIT_MATURED:
if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.MATURED, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be matured from " + from.getCode();
throw new InvalidDepositStateTransitionException("mature", "failed", errorMessage, from);
}
break;
case DEPOSIT_CLOSED:
if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.CLOSED, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be closed from " + from.getCode();
throw new InvalidDepositStateTransitionException("closed", "failed", errorMessage, from);
}
break;
case DEPOSIT_PRECLOSED:
if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
newState = stateOf(DepositAccountStatus.PRECLOSED, allowedDepositStatuses);
} else {
final String errorMessage = "The DepositApplication can not be matured from " + from.getCode();
throw new InvalidDepositStateTransitionException("preclosure", "failed", errorMessage, from);
}
break;
default:
break;
}
return newState;
}
private DepositAccountStatus stateOf(DepositAccountStatus state, List<DepositAccountStatus> allowedLoanStatuses) {
DepositAccountStatus match = null;
for (DepositAccountStatus depositStatus : allowedLoanStatuses) {
if (depositStatus.hasStateOf(state)) {
match = depositStatus;
break;
}
}
return match;
}
private boolean anyOfAllowedWhenComingFrom(final DepositAccountStatus state, final DepositAccountStatus... allowedStates) {
boolean allowed = false;
for (DepositAccountStatus allowedState : allowedStates) {
if (state.hasStateOf(allowedState)) {
allowed = true;
break;
}
}
return allowed;
}
} }
@@ -11,88 +11,91 @@ import org.springframework.stereotype.Service;
@Service @Service
public class FixedTermDepositInterestCalculator { public class FixedTermDepositInterestCalculator {
// FIXME - MADHUKAR - Are the unused field here needed? // FIXME - MADHUKAR - Are the unused field here needed?
public Money calculateInterestOnMaturityFor( public Money calculateInterestOnMaturityFor(final Money deposit, final Integer tenureInMonths, final BigDecimal maturityInterestRate,
final Money deposit, final Integer interestCompoundedEvery, final PeriodFrequencyType interestCompoundedFrequencyPeriodType) {
final Integer tenureInMonths,
final BigDecimal maturityInterestRate,
final Integer interestCompoundedEvery,
final PeriodFrequencyType interestCompoundedFrequencyPeriodType) {
// TODO - Can change 'interest compounding' fields into something simpler like interestCompoundedFrequency {None (Simple Interest), Monthly, Quarterly, Half-Yearly, Annually} // TODO - Can change 'interest compounding' fields into something
// - the 'interestCompoundedEvery' would then be inferred form the selected type. // simpler like interestCompoundedFrequency {None (Simple Interest),
// - the special case of 'simple interest' or 'no compounding' would use simple formula rather than 'future value' function. // Monthly, Quarterly, Half-Yearly, Annually}
// - the 'interestCompoundedEvery' would then be inferred form the
// FIXME - assuming only monthly compounding period for now // selected type.
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); // - the special case of 'simple interest' or 'no compounding' would use
Integer monthsInYear = 12; // simple formula rather than 'future value' function.
BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc);
BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()), mc);
Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery;
return fv(ratePerCompoundingPeriod, numberOfPeriods, deposit);
}
private static Money fv(final BigDecimal ratePerCompoundingPeriod, final Integer numberOfPeriods, final Money presentValue) { // FIXME - assuming only monthly compounding period for now
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
double pmtPerPeriod = Double.valueOf("0.0"); Integer monthsInYear = 12;
double pv = presentValue.negated().getAmount().doubleValue();
double futureValue = fv(ratePerCompoundingPeriod.doubleValue(), numberOfPeriods.doubleValue(), pmtPerPeriod, pv, false);
return Money.of(presentValue.getCurrency(), BigDecimal.valueOf(futureValue));
}
/**
* Future value of an amount given the number of payments, rate, amount of
* individual payment, present value and boolean value indicating whether
* payments are due at the beginning of period (false => payments are due at
* end of period)
*/
private static double fv(double ratePeriodCompoundingPeriod, double numberOfCompoundingPeriods, double pmtPerPeriod, double presentValue, boolean type) {
double retval = 0;
if (ratePeriodCompoundingPeriod == 0) {
retval = -1 * (presentValue + (numberOfCompoundingPeriods * pmtPerPeriod));
} else {
double r1 = ratePeriodCompoundingPeriod + 1;
retval = ((1 - Math.pow(r1, numberOfCompoundingPeriods)) * (type ? r1 : 1) * pmtPerPeriod) / ratePeriodCompoundingPeriod - presentValue
* Math.pow(r1, numberOfCompoundingPeriods);
}
return retval;
}
public Money calculateInterestOnMaturityForSimpleInterest(Money deposit, BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc);
Integer tenureInMonths, BigDecimal maturityInterestRate, BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc);
Integer interestCompoundedEvery,
PeriodFrequencyType interestCompoundedFrequencyPeriodType) { BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()),
mc);
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer monthsInYear = 12; Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery;
BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc); return fv(ratePerCompoundingPeriod, numberOfPeriods, deposit);
BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc); }
BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()), mc);
Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery; private static Money fv(final BigDecimal ratePerCompoundingPeriod, final Integer numberOfPeriods, final Money presentValue) {
BigDecimal interest = ratePerCompoundingPeriod.multiply(deposit.getAmount()).multiply(BigDecimal.valueOf(new Double(numberOfPeriods))); double pmtPerPeriod = Double.valueOf("0.0");
BigDecimal totalAmount =deposit.getAmount().add(interest); double pv = presentValue.negated().getAmount().doubleValue();
return Money.of(deposit.getCurrency(), totalAmount); double futureValue = fv(ratePerCompoundingPeriod.doubleValue(), numberOfPeriods.doubleValue(), pmtPerPeriod, pv, false);
}
return Money.of(presentValue.getCurrency(), BigDecimal.valueOf(futureValue));
public Money calculateRemainInterest(Money deposit, Integer days, BigDecimal interestRate){ }
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); /**
Integer daysInYear = 365; * Future value of an amount given the number of payments, rate, amount of
* individual payment, present value and boolean value indicating whether
BigDecimal interestRateAsFraction = interestRate.divide(BigDecimal.valueOf(100), mc); * payments are due at the beginning of period (false => payments are due at
BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc); * end of period)
BigDecimal interest = BigDecimal.valueOf(deposit.getAmount().doubleValue()*days.doubleValue()*interestRateForOneDay.doubleValue()); */
private static double fv(double ratePeriodCompoundingPeriod, double numberOfCompoundingPeriods, double pmtPerPeriod,
return Money.of(deposit.getCurrency(), interest); double presentValue, boolean type) {
} double retval = 0;
if (ratePeriodCompoundingPeriod == 0) {
retval = -1 * (presentValue + (numberOfCompoundingPeriods * pmtPerPeriod));
} else {
double r1 = ratePeriodCompoundingPeriod + 1;
retval = ((1 - Math.pow(r1, numberOfCompoundingPeriods)) * (type ? r1 : 1) * pmtPerPeriod) / ratePeriodCompoundingPeriod
- presentValue * Math.pow(r1, numberOfCompoundingPeriods);
}
return retval;
}
public Money calculateInterestOnMaturityForSimpleInterest(Money deposit, Integer tenureInMonths, BigDecimal maturityInterestRate,
Integer interestCompoundedEvery, PeriodFrequencyType interestCompoundedFrequencyPeriodType) {
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer monthsInYear = 12;
BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc);
BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()),
mc);
Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery;
BigDecimal interest = ratePerCompoundingPeriod.multiply(deposit.getAmount()).multiply(
BigDecimal.valueOf(new Double(numberOfPeriods)));
BigDecimal totalAmount = deposit.getAmount().add(interest);
return Money.of(deposit.getCurrency(), totalAmount);
}
public Money calculateRemainInterest(Money deposit, Integer days, BigDecimal interestRate) {
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer daysInYear = 365;
BigDecimal interestRateAsFraction = interestRate.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc);
BigDecimal interest = BigDecimal.valueOf(deposit.getAmount().doubleValue() * days.doubleValue()
* interestRateForOneDay.doubleValue());
return Money.of(deposit.getCurrency(), interest);
}
} }
@@ -4,11 +4,11 @@ import java.math.BigDecimal;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException;
public class DepositAccounDataValidationtException extends public class DepositAccounDataValidationtException extends AbstractPlatformDomainRuleException {
AbstractPlatformDomainRuleException {
public DepositAccounDataValidationtException(BigDecimal preClosureInterestRate, BigDecimal maturityMinInterestRate) {
super("error.msg.deposit.account.preClosureInterestRate.should.lessthanOrEqualTo.maturityMinInterestRate", "PreClosureInterestRate : "+preClosureInterestRate+"should lessthan or equal to maturityMinInterestRate : "+maturityMinInterestRate, preClosureInterestRate,maturityMinInterestRate);
}
public DepositAccounDataValidationtException(BigDecimal preClosureInterestRate, BigDecimal maturityMinInterestRate) {
super("error.msg.deposit.account.preClosureInterestRate.should.lessthanOrEqualTo.maturityMinInterestRate",
"PreClosureInterestRate : " + preClosureInterestRate + "should lessthan or equal to maturityMinInterestRate : "
+ maturityMinInterestRate, preClosureInterestRate, maturityMinInterestRate);
}
} }
@@ -4,8 +4,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN
public class DepositAccountNotFoundException extends AbstractPlatformResourceNotFoundException { public class DepositAccountNotFoundException extends AbstractPlatformResourceNotFoundException {
public DepositAccountNotFoundException(final Long id) { public DepositAccountNotFoundException(final Long id) {
super("error.msg.deposit.account.id.invalid", "Deposit account with identifier " + id + " does not exist", id); super("error.msg.deposit.account.id.invalid", "Deposit account with identifier " + id + " does not exist", id);
} }
}
}
@@ -3,10 +3,9 @@ package org.mifosplatform.portfolio.savingsdepositaccount.exception;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException;
public class DepositAccountReopenException extends AbstractPlatformDomainRuleException{ public class DepositAccountReopenException extends AbstractPlatformDomainRuleException {
public DepositAccountReopenException(LocalDate maturedDate) {
super("error.msg.depositaccount.cannot.reopen.before.mature", "You cannot renew the account that is not matured:"+maturedDate);
}
public DepositAccountReopenException(LocalDate maturedDate) {
super("error.msg.depositaccount.cannot.reopen.before.mature", "You cannot renew the account that is not matured:" + maturedDate);
}
} }
@@ -2,11 +2,9 @@ package org.mifosplatform.portfolio.savingsdepositaccount.exception;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException;
public class DepositAccountTransactionsException extends AbstractPlatformDomainRuleException { public class DepositAccountTransactionsException extends AbstractPlatformDomainRuleException {
public DepositAccountTransactionsException(String errorcode, String remainInterestForWithdrawal) { public DepositAccountTransactionsException(String errorcode, String remainInterestForWithdrawal) {
super(errorcode, "You can Withdraw "+remainInterestForWithdrawal+" only", remainInterestForWithdrawal); super(errorcode, "You can Withdraw " + remainInterestForWithdrawal + " only", remainInterestForWithdrawal);
} }
} }
@@ -8,5 +8,4 @@ public class InvalidDepositStateTransitionException extends AbstractPlatformDoma
Object... defaultUserMessageArgs) { Object... defaultUserMessageArgs) {
super("error.msg.deposit." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); super("error.msg.deposit." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs);
} }
}
}
@@ -24,324 +24,314 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* An assembler for turning {@link DepositAccountCommand} into {@link DepositAccount}'s. * An assembler for turning {@link DepositAccountCommand} into
* {@link DepositAccount}'s.
*/ */
@Service @Service
public class DepositAccountAssembler { public class DepositAccountAssembler {
private final ClientRepository clientRepository; private final ClientRepository clientRepository;
private final DepositProductRepository depositProductRepository; private final DepositProductRepository depositProductRepository;
private final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator; private final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator;
@Autowired @Autowired
public DepositAccountAssembler(final ClientRepository clientRepository, final DepositProductRepository depositProductRepository, public DepositAccountAssembler(final ClientRepository clientRepository, final DepositProductRepository depositProductRepository,
final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator) { final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator) {
this.clientRepository = clientRepository; this.clientRepository = clientRepository;
this.depositProductRepository = depositProductRepository; this.depositProductRepository = depositProductRepository;
this.fixedTermDepositInterestCalculator = fixedTermDepositInterestCalculator; this.fixedTermDepositInterestCalculator = fixedTermDepositInterestCalculator;
} }
public DepositAccount assembleFrom(final DepositAccountCommand command) { public DepositAccount assembleFrom(final DepositAccountCommand command) {
Client client = this.clientRepository.findOne(command.getClientId()); Client client = this.clientRepository.findOne(command.getClientId());
if (client == null || client.isDeleted()) { if (client == null || client.isDeleted()) { throw new ClientNotFoundException(command.getClientId()); }
throw new ClientNotFoundException(command.getClientId());
}
DepositProduct product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) {
throw new DepositProductNotFoundException(command.getProductId());
}
boolean isInterestWithdrawable = command.isInterestWithdrawable();
// details inherited from product setting (unless allowed to be overridden through account creation api
Money deposit = Money.of(product.getCurrency(), command.getDepositAmount());
Integer tenureInMonths = product.getTenureInMonths();
if (command.getTenureInMonths() != null) {
tenureInMonths = command.getTenureInMonths();
}
BigDecimal maturityInterestRate = product.getMaturityDefaultInterestRate();
if (command.getMaturityInterestRate() != null) {
maturityInterestRate = command.getMaturityInterestRate();
}
BigDecimal preClosureInterestRate = product.getPreClosureInterestRate();
if(command.getPreClosureInterestRate()!=null){
preClosureInterestRate = command.getPreClosureInterestRate();
}
if(product.getMaturityMinInterestRate().compareTo(preClosureInterestRate)==-1){
throw new DepositAccounDataValidationtException(preClosureInterestRate, product.getMaturityMinInterestRate());
}
Integer compoundingInterestEvery = product.getInterestCompoundedEvery();
if (command.getInterestCompoundedEvery() != null) {
compoundingInterestEvery = command.getInterestCompoundedEvery();
}
PeriodFrequencyType compoundingInterestFrequency = product.getInterestCompoundedEveryPeriodType();
if (command.getInterestCompoundedEveryPeriodType() != null) {
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
boolean renewalAllowed = product.isRenewalAllowed();
if (command.isRenewalAllowedChanged()) {
renewalAllowed = command.isRenewalAllowed();
}
boolean preClosureAllowed = product.isPreClosureAllowed();
if (command.isPreClosureAllowedChanged()) {
preClosureAllowed = command.isPreClosureAllowed();
}
boolean interestCompoundingAllowed= product.isInterestCompoundingAllowed();
if(command.isInterestCompoundingAllowedChanged()){
interestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean isLockinPeriodAllowed = product.isLockinPeriodAllowed();
if(command.isLockinPeriodChanged()){
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = product.getLockinPeriod();
if(command.getLockinPeriod() != null){
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = product.getLockinPeriodType();
if(command.getLockinPeriodType() != null){
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
// end of details allowed to be overriden from product
DepositAccount account =new DepositAccount().openNew(client, product, command.getExternalId(),
deposit,
maturityInterestRate, preClosureInterestRate,
tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency,
command.getCommencementDate(),
renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator,
defaultDepositLifecycleStateMachine(),isInterestWithdrawable,interestCompoundingAllowed,
isLockinPeriodAllowed,lockinPeriod,lockinPeriodType);
return account;
}
private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() {
List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values());
return new DepositLifecycleStateMachineImpl(allowedDepositStatuses);
}
public DepositAccount assembleFrom(DepositAccount account, DepositAccountCommand command) { DepositProduct product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(command.getProductId()); }
Client client = account.client();
DepositProduct product = account.product();
if(command.getProductId() != null){
product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) {
throw new DepositProductNotFoundException(command.getProductId());
}
}
Money deposit = account.getDeposit();
if(command.getDepositAmount() != null){
deposit = Money.of(account.getDeposit().getCurrency(), command.getDepositAmount());
}
Integer tenureInMonths = account.getTenureInMonths();
if(command.getTenureInMonths() != null){
tenureInMonths =command.getTenureInMonths();
}
BigDecimal maturityInterestRate = account.getInterestRate();
if(command.getMaturityInterestRate() != null){
maturityInterestRate = command.getMaturityInterestRate();
}
BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
if(command.getPreClosureInterestRate() != null){
preClosureInterestRate = command.getPreClosureInterestRate();
}
if(product.getMaturityMinInterestRate().compareTo(preClosureInterestRate)==-1){
throw new DepositAccounDataValidationtException(preClosureInterestRate, product.getMaturityMinInterestRate());
}
Integer compoundingInterestEvery = account.getInterestCompoundedEvery();
if(command.getInterestCompoundedEvery() != null){
compoundingInterestEvery = command.getInterestCompoundedEvery();
}
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType();
if(command.getInterestCompoundedEveryPeriodType() !=null){
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
boolean renewalAllowed = account.isRenewalAllowed();
if(command.isRenewalAllowedChanged()){
renewalAllowed = command.isRenewalAllowed();
}
boolean preClosureAllowed = account.isPreClosureAllowed();
if(command.isPreClosureAllowedChanged()){
preClosureAllowed = command.isPreClosureAllowed();
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
if(command.isInterestWithdrawableChanged()){
isInterestWithdrawable = command.isInterestWithdrawable();
}
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed();
if(command.isInterestCompoundingAllowedChanged()){
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
if(command.isLockinPeriodChanged()){
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = account.getLockinPeriod();
if(command.getLockinPeriod() != null){
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
if(command.getLockinPeriodType() != null){
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
DepositAccount newAccount =new DepositAccount().openNew(client, product, null,
deposit,
maturityInterestRate, preClosureInterestRate,
tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency,
account.maturesOnDate().plusDays(1),
renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator, defaultDepositLifecycleStateMachine(),
isInterestWithdrawable,isInterestCompoundingAllowed,isLockinPeriodAllowed,lockinPeriod,lockinPeriodType);
newAccount.updateAccount(account);
return newAccount;
}
/*public void adjustTotalAmountForPreclosureInterest(DepositAccount account,LocalDate eventDate) { boolean isInterestWithdrawable = command.isInterestWithdrawable();
account.adjustTotalAmountForPreclosureInterest(account,this.fixedTermDepositInterestCalculator,eventDate);
}*/
public void assembleUpdatedDepositAccount(DepositAccount account,DepositAccountCommand command) { // details inherited from product setting (unless allowed to be
// overridden through account creation api
DepositProduct product = account.product(); Money deposit = Money.of(product.getCurrency(), command.getDepositAmount());
if(command.getProductId() != null){
product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) {
throw new DepositProductNotFoundException(command.getProductId());
}
}
String externalId = account.getExternalId();
if(command.isExternalIdChanged()){
externalId = command.getExternalId();
}
LocalDate commencementDate = account.getProjectedCommencementDate();
if(command.isCommencementDateChanged()){
commencementDate = new LocalDate(command.getCommencementDate());
}
Money deposit = account.getDeposit();
if(command.isDepositAmountChanged()){
deposit = Money.of(product.getCurrency(), command.getDepositAmount());
}
Integer tenureInMonths = account.getTenureInMonths();
if(command.isTenureInMonthsChanged()){
tenureInMonths =command.getTenureInMonths();
}
BigDecimal maturityInterestRate = account.getInterestRate();
if(command.isMaturityActualInterestRateChanged()){
maturityInterestRate = command.getMaturityInterestRate();
}
BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
if(command.isPreClosureInterestRateChanged()){
preClosureInterestRate = command.getPreClosureInterestRate();
}
if(product.getMaturityMinInterestRate().compareTo(preClosureInterestRate)==-1){
throw new DepositAccounDataValidationtException(preClosureInterestRate, product.getMaturityMinInterestRate());
}
Integer compoundingInterestEvery = account.getInterestCompoundedEvery();
if(command.isCompoundingInterestEveryChanged()){
compoundingInterestEvery = command.getInterestCompoundedEvery();
}
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType();
if(command.getInterestCompoundedEveryPeriodType() !=null){
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
boolean renewalAllowed = account.isRenewalAllowed();
if(command.isRenewalAllowedChanged()){
renewalAllowed = command.isRenewalAllowed();
}
boolean preClosureAllowed = account.isPreClosureAllowed();
if(command.isPreClosureAllowedChanged()){
preClosureAllowed = command.isPreClosureAllowed();
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
if(command.isInterestWithdrawableChanged()){
isInterestWithdrawable = command.isInterestWithdrawable();
}
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed();
if(command.isInterestCompoundingAllowedChanged()){
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
if(command.isLockinPeriodChanged()){
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = account.getLockinPeriod();
if(command.getLockinPeriod() != null){
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
if(command.getLockinPeriodType() != null){
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
account.update(product,externalId,commencementDate,deposit,tenureInMonths,maturityInterestRate,preClosureInterestRate,compoundingInterestEvery,compoundingInterestFrequency,renewalAllowed,
preClosureAllowed,isInterestWithdrawable,isInterestCompoundingAllowed,this.fixedTermDepositInterestCalculator,isLockinPeriodAllowed,lockinPeriod,lockinPeriodType);
}
public void updateApprovedDepositAccount(DepositAccount account, DepositAccountCommand command) { Integer tenureInMonths = product.getTenureInMonths();
if (command.getTenureInMonths() != null) {
boolean renewalAllowed = account.isRenewalAllowed(); tenureInMonths = command.getTenureInMonths();
if(command.isRenewalAllowedChanged()){ }
renewalAllowed = command.isRenewalAllowed();
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
if(command.isInterestWithdrawableChanged()){
isInterestWithdrawable = command.isInterestWithdrawable();
}
account.update(renewalAllowed,isInterestWithdrawable);
}
public void postInterest(DepositAccount account) { BigDecimal maturityInterestRate = product.getMaturityDefaultInterestRate();
account.postInterestForDepositAccount(account,this.fixedTermDepositInterestCalculator); if (command.getMaturityInterestRate() != null) {
} maturityInterestRate = command.getMaturityInterestRate();
}
BigDecimal preClosureInterestRate = product.getPreClosureInterestRate();
if (command.getPreClosureInterestRate() != null) {
preClosureInterestRate = command.getPreClosureInterestRate();
}
if (product.getMaturityMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException(
preClosureInterestRate, product.getMaturityMinInterestRate()); }
Integer compoundingInterestEvery = product.getInterestCompoundedEvery();
if (command.getInterestCompoundedEvery() != null) {
compoundingInterestEvery = command.getInterestCompoundedEvery();
}
PeriodFrequencyType compoundingInterestFrequency = product.getInterestCompoundedEveryPeriodType();
if (command.getInterestCompoundedEveryPeriodType() != null) {
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
boolean renewalAllowed = product.isRenewalAllowed();
if (command.isRenewalAllowedChanged()) {
renewalAllowed = command.isRenewalAllowed();
}
boolean preClosureAllowed = product.isPreClosureAllowed();
if (command.isPreClosureAllowedChanged()) {
preClosureAllowed = command.isPreClosureAllowed();
}
boolean interestCompoundingAllowed = product.isInterestCompoundingAllowed();
if (command.isInterestCompoundingAllowedChanged()) {
interestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean isLockinPeriodAllowed = product.isLockinPeriodAllowed();
if (command.isLockinPeriodChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = product.getLockinPeriod();
if (command.getLockinPeriod() != null) {
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = product.getLockinPeriodType();
if (command.getLockinPeriodType() != null) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
// end of details allowed to be overriden from product
DepositAccount account = new DepositAccount().openNew(client, product, command.getExternalId(), deposit, maturityInterestRate,
preClosureInterestRate, tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency,
command.getCommencementDate(), renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator,
defaultDepositLifecycleStateMachine(), isInterestWithdrawable, interestCompoundingAllowed, isLockinPeriodAllowed,
lockinPeriod, lockinPeriodType);
return account;
}
private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() {
List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values());
return new DepositLifecycleStateMachineImpl(allowedDepositStatuses);
}
public DepositAccount assembleFrom(DepositAccount account, DepositAccountCommand command) {
Client client = account.client();
DepositProduct product = account.product();
if (command.getProductId() != null) {
product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(command.getProductId()); }
}
Money deposit = account.getDeposit();
if (command.getDepositAmount() != null) {
deposit = Money.of(account.getDeposit().getCurrency(), command.getDepositAmount());
}
Integer tenureInMonths = account.getTenureInMonths();
if (command.getTenureInMonths() != null) {
tenureInMonths = command.getTenureInMonths();
}
BigDecimal maturityInterestRate = account.getInterestRate();
if (command.getMaturityInterestRate() != null) {
maturityInterestRate = command.getMaturityInterestRate();
}
BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
if (command.getPreClosureInterestRate() != null) {
preClosureInterestRate = command.getPreClosureInterestRate();
}
if (product.getMaturityMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException(
preClosureInterestRate, product.getMaturityMinInterestRate()); }
Integer compoundingInterestEvery = account.getInterestCompoundedEvery();
if (command.getInterestCompoundedEvery() != null) {
compoundingInterestEvery = command.getInterestCompoundedEvery();
}
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType();
if (command.getInterestCompoundedEveryPeriodType() != null) {
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
boolean renewalAllowed = account.isRenewalAllowed();
if (command.isRenewalAllowedChanged()) {
renewalAllowed = command.isRenewalAllowed();
}
boolean preClosureAllowed = account.isPreClosureAllowed();
if (command.isPreClosureAllowedChanged()) {
preClosureAllowed = command.isPreClosureAllowed();
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
if (command.isInterestWithdrawableChanged()) {
isInterestWithdrawable = command.isInterestWithdrawable();
}
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed();
if (command.isInterestCompoundingAllowedChanged()) {
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
if (command.isLockinPeriodChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = account.getLockinPeriod();
if (command.getLockinPeriod() != null) {
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
if (command.getLockinPeriodType() != null) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
DepositAccount newAccount = new DepositAccount().openNew(client, product, null, deposit, maturityInterestRate,
preClosureInterestRate, tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency, account.maturesOnDate()
.plusDays(1), renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator,
defaultDepositLifecycleStateMachine(), isInterestWithdrawable, isInterestCompoundingAllowed, isLockinPeriodAllowed,
lockinPeriod, lockinPeriodType);
newAccount.updateAccount(account);
return newAccount;
}
/*
* public void adjustTotalAmountForPreclosureInterest(DepositAccount
* account,LocalDate eventDate) {
* account.adjustTotalAmountForPreclosureInterest
* (account,this.fixedTermDepositInterestCalculator,eventDate); }
*/
public void assembleUpdatedDepositAccount(DepositAccount account, DepositAccountCommand command) {
DepositProduct product = account.product();
if (command.getProductId() != null) {
product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(command.getProductId()); }
}
String externalId = account.getExternalId();
if (command.isExternalIdChanged()) {
externalId = command.getExternalId();
}
LocalDate commencementDate = account.getProjectedCommencementDate();
if (command.isCommencementDateChanged()) {
commencementDate = new LocalDate(command.getCommencementDate());
}
Money deposit = account.getDeposit();
if (command.isDepositAmountChanged()) {
deposit = Money.of(product.getCurrency(), command.getDepositAmount());
}
Integer tenureInMonths = account.getTenureInMonths();
if (command.isTenureInMonthsChanged()) {
tenureInMonths = command.getTenureInMonths();
}
BigDecimal maturityInterestRate = account.getInterestRate();
if (command.isMaturityActualInterestRateChanged()) {
maturityInterestRate = command.getMaturityInterestRate();
}
BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
if (command.isPreClosureInterestRateChanged()) {
preClosureInterestRate = command.getPreClosureInterestRate();
}
if (product.getMaturityMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException(
preClosureInterestRate, product.getMaturityMinInterestRate()); }
Integer compoundingInterestEvery = account.getInterestCompoundedEvery();
if (command.isCompoundingInterestEveryChanged()) {
compoundingInterestEvery = command.getInterestCompoundedEvery();
}
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType();
if (command.getInterestCompoundedEveryPeriodType() != null) {
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
boolean renewalAllowed = account.isRenewalAllowed();
if (command.isRenewalAllowedChanged()) {
renewalAllowed = command.isRenewalAllowed();
}
boolean preClosureAllowed = account.isPreClosureAllowed();
if (command.isPreClosureAllowedChanged()) {
preClosureAllowed = command.isPreClosureAllowed();
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
if (command.isInterestWithdrawableChanged()) {
isInterestWithdrawable = command.isInterestWithdrawable();
}
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed();
if (command.isInterestCompoundingAllowedChanged()) {
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
if (command.isLockinPeriodChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
Integer lockinPeriod = account.getLockinPeriod();
if (command.getLockinPeriod() != null) {
lockinPeriod = command.getLockinPeriod();
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
if (command.getLockinPeriodType() != null) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
account.update(product, externalId, commencementDate, deposit, tenureInMonths, maturityInterestRate, preClosureInterestRate,
compoundingInterestEvery, compoundingInterestFrequency, renewalAllowed, preClosureAllowed, isInterestWithdrawable,
isInterestCompoundingAllowed, this.fixedTermDepositInterestCalculator, isLockinPeriodAllowed, lockinPeriod,
lockinPeriodType);
}
public void updateApprovedDepositAccount(DepositAccount account, DepositAccountCommand command) {
boolean renewalAllowed = account.isRenewalAllowed();
if (command.isRenewalAllowedChanged()) {
renewalAllowed = command.isRenewalAllowed();
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
if (command.isInterestWithdrawableChanged()) {
isInterestWithdrawable = command.isInterestWithdrawable();
}
account.update(renewalAllowed, isInterestWithdrawable);
}
public void postInterest(DepositAccount account) {
account.postInterestForDepositAccount(account, this.fixedTermDepositInterestCalculator);
}
} }
@@ -5,41 +5,52 @@ import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountSt
public class DepositAccountEnumerations { public class DepositAccountEnumerations {
public static EnumOptionData status(final Integer statusId) { public static EnumOptionData status(final Integer statusId) {
return status(DepositAccountStatus.fromInt(statusId)); return status(DepositAccountStatus.fromInt(statusId));
} }
public static EnumOptionData status(final DepositAccountStatus status) { public static EnumOptionData status(final DepositAccountStatus status) {
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (status) { switch (status) {
case SUBMITED_AND_PENDING_APPROVAL: case SUBMITED_AND_PENDING_APPROVAL:
optionData = new EnumOptionData(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue().longValue(), DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval"); optionData = new EnumOptionData(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue().longValue(),
break; DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval");
/*case APPROVED: break;
optionData = new EnumOptionData(DepositAccountStatus.APPROVED.getValue().longValue(), DepositAccountStatus.APPROVED.getCode(), "Approved"); /*
break;*/ * case APPROVED: optionData = new
case ACTIVE: * EnumOptionData(DepositAccountStatus
optionData = new EnumOptionData(DepositAccountStatus.ACTIVE.getValue().longValue(), DepositAccountStatus.ACTIVE.getCode(), "Active"); * .APPROVED.getValue().longValue(),
break; * DepositAccountStatus.APPROVED.getCode(), "Approved"); break;
case REJECTED: */
optionData = new EnumOptionData(DepositAccountStatus.REJECTED.getValue().longValue(), DepositAccountStatus.REJECTED.getCode(), "Rejected"); case ACTIVE:
break; optionData = new EnumOptionData(DepositAccountStatus.ACTIVE.getValue().longValue(), DepositAccountStatus.ACTIVE.getCode(),
case WITHDRAWN_BY_CLIENT: "Active");
optionData = new EnumOptionData(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue().longValue(), DepositAccountStatus.WITHDRAWN_BY_CLIENT.getCode(), "Withdrawn by applicant"); break;
break; case REJECTED:
case MATURED: optionData = new EnumOptionData(DepositAccountStatus.REJECTED.getValue().longValue(),
optionData = new EnumOptionData(DepositAccountStatus.MATURED.getValue().longValue(), DepositAccountStatus.MATURED.getCode(), "Matured"); DepositAccountStatus.REJECTED.getCode(), "Rejected");
break; break;
case CLOSED: case WITHDRAWN_BY_CLIENT:
optionData = new EnumOptionData(DepositAccountStatus.CLOSED.getValue().longValue(), DepositAccountStatus.CLOSED.getCode(), "Closed"); optionData = new EnumOptionData(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue().longValue(),
break; DepositAccountStatus.WITHDRAWN_BY_CLIENT.getCode(), "Withdrawn by applicant");
case PRECLOSED: break;
optionData = new EnumOptionData(DepositAccountStatus.PRECLOSED.getValue().longValue(), DepositAccountStatus.PRECLOSED.getCode(), "Preclosed"); case MATURED:
break; optionData = new EnumOptionData(DepositAccountStatus.MATURED.getValue().longValue(),
default: DepositAccountStatus.MATURED.getCode(), "Matured");
optionData = new EnumOptionData(DepositAccountStatus.INVALID.getValue().longValue(), DepositAccountStatus.INVALID.getCode(), "Invalid"); break;
break; case CLOSED:
} optionData = new EnumOptionData(DepositAccountStatus.CLOSED.getValue().longValue(), DepositAccountStatus.CLOSED.getCode(),
return optionData; "Closed");
} break;
case PRECLOSED:
optionData = new EnumOptionData(DepositAccountStatus.PRECLOSED.getValue().longValue(),
DepositAccountStatus.PRECLOSED.getCode(), "Preclosed");
break;
default:
optionData = new EnumOptionData(DepositAccountStatus.INVALID.getValue().longValue(),
DepositAccountStatus.INVALID.getCode(), "Invalid");
break;
}
return optionData;
}
} }
@@ -18,6 +18,6 @@ public interface DepositAccountReadPlatformService {
DepositPermissionData retrieveDepositAccountsPermissions(DepositAccountData depositAccountData); DepositPermissionData retrieveDepositAccountsPermissions(DepositAccountData depositAccountData);
BigDecimal retrieveAvailableInterestForWithdrawal(DepositAccountData account); BigDecimal retrieveAvailableInterestForWithdrawal(DepositAccountData account);
Collection<DepositAccountsForLookup> retrieveDepositAccountForLookup(); Collection<DepositAccountsForLookup> retrieveDepositAccountForLookup();
} }
@@ -208,18 +208,19 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod"); Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod");
Integer lockinPeriodTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodType"); Integer lockinPeriodTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodType");
EnumOptionData lockinPeriodType = SavingsDepositEnumerations.interestCompoundingPeriodType(lockinPeriodTypeValue); EnumOptionData lockinPeriodType = SavingsDepositEnumerations.interestCompoundingPeriodType(lockinPeriodTypeValue);
BigDecimal availableInterest = rs.getBigDecimal("availableInterest"); BigDecimal availableInterest = rs.getBigDecimal("availableInterest");
BigDecimal interestPostedAmount = rs.getBigDecimal("interestPostedAmount"); BigDecimal interestPostedAmount = rs.getBigDecimal("interestPostedAmount");
LocalDate lastInterestPostedDate = JdbcSupport.getLocalDate(rs, "lastInterestPostedDate"); LocalDate lastInterestPostedDate = JdbcSupport.getLocalDate(rs, "lastInterestPostedDate");
LocalDate nextInterestPostedDate = JdbcSupport.getLocalDate(rs, "nextInterestPostedDate"); LocalDate nextInterestPostedDate = JdbcSupport.getLocalDate(rs, "nextInterestPostedDate");
return new DepositAccountData(id, externalId, status, clientId, clientName, productId, productName, currencyData, return new DepositAccountData(id, externalId, status, clientId, clientName, productId, productName, currencyData,
depositAmount, interestRate, termInMonths, projectedCommencementDate, actualCommencementDate, maturedOn, depositAmount, interestRate, termInMonths, projectedCommencementDate, actualCommencementDate, maturedOn,
projectedInterestAccrued, actualInterestAccrued, projectedMaturityAmount, actualMaturityAmount, projectedInterestAccrued, actualInterestAccrued, projectedMaturityAmount, actualMaturityAmount,
interestCompoundedEvery, interestCompoundedEveryPeriodType, renewalAllowed, preClosureAllowed, preClosureInterestRate, interestCompoundedEvery, interestCompoundedEveryPeriodType, renewalAllowed, preClosureAllowed, preClosureInterestRate,
withdrawnonDate, rejectedonDate, closedonDate, isInterestWithdrawable, interestPaid, interestCompoundingAllowed, withdrawnonDate, rejectedonDate, closedonDate, isInterestWithdrawable, interestPaid, interestCompoundingAllowed,
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, availableInterest, interestPostedAmount, lastInterestPostedDate, nextInterestPostedDate); isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, availableInterest, interestPostedAmount, lastInterestPostedDate,
nextInterestPostedDate);
} }
} }
@@ -254,7 +255,18 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
boolean undoApprovalAllowed = (depositAccountData.getStatus().getId().equals(300L)); boolean undoApprovalAllowed = (depositAccountData.getStatus().getId().equals(300L));
boolean renewelAllowed = false; boolean renewelAllowed = false;
if (depositAccountData.getMaturedOn() != null) { if (depositAccountData.getMaturedOn() != null) {
if (new LocalDate().isAfter(depositAccountData.getMaturedOn())/* || depositAccountData.getMaturedOn().isEqual(new LocalDate()) */) { if (new LocalDate().isAfter(depositAccountData.getMaturedOn())/*
* ||
* depositAccountData
* .
* getMaturedOn
* ().
* isEqual
* (
* new
* LocalDate
* ())
*/) {
renewelAllowed = depositAccountData.isRenewalAllowed(); renewelAllowed = depositAccountData.isRenewalAllowed();
} }
} }
@@ -276,28 +288,28 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
return BigDecimal.valueOf(interstGettingForPeriod.multiply(new BigDecimal(noOfPeriods)).doubleValue() return BigDecimal.valueOf(interstGettingForPeriod.multiply(new BigDecimal(noOfPeriods)).doubleValue()
- account.getInterestPaid().doubleValue()); - account.getInterestPaid().doubleValue());
} }
@Override @Override
public Collection<DepositAccountsForLookup> retrieveDepositAccountForLookup() { public Collection<DepositAccountsForLookup> retrieveDepositAccountForLookup() {
this.context.authenticatedUser(); this.context.authenticatedUser();
DepositAccountLookupMapper mapper = new DepositAccountLookupMapper(); DepositAccountLookupMapper mapper = new DepositAccountLookupMapper();
String sql = "select "+mapper.depositAccountLookupSchema(); String sql = "select " + mapper.depositAccountLookupSchema();
return this.jdbcTemplate.query(sql, mapper, new Object[]{}); return this.jdbcTemplate.query(sql, mapper, new Object[] {});
}
private static final class DepositAccountLookupMapper implements RowMapper<DepositAccountsForLookup> {
public String depositAccountLookupSchema(){
return " da.id as id from m_deposit_account da where da.status_enum=300 and da.is_deleted=0";
}
@Override }
public DepositAccountsForLookup mapRow(ResultSet rs, int rowNum) throws SQLException {
Long id = rs.getLong("id"); private static final class DepositAccountLookupMapper implements RowMapper<DepositAccountsForLookup> {
return new DepositAccountsForLookup(id);
} public String depositAccountLookupSchema() {
return " da.id as id from m_deposit_account da where da.status_enum=300 and da.is_deleted=0";
} }
@Override
public DepositAccountsForLookup mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException {
Long id = rs.getLong("id");
return new DepositAccountsForLookup(id);
}
}
} }
@@ -4,31 +4,35 @@ import org.mifosplatform.infrastructure.core.data.EnumOptionData;
import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountTransactionType; import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountTransactionType;
public class DepositAccountTransactionEnumerations { public class DepositAccountTransactionEnumerations {
public static EnumOptionData depositType(final Integer statusId) {
return depositType(DepositAccountTransactionType.fromInt(statusId));
}
private static EnumOptionData depositType(DepositAccountTransactionType transactionType) { public static EnumOptionData depositType(final Integer statusId) {
return depositType(DepositAccountTransactionType.fromInt(statusId));
EnumOptionData optionData=null; }
switch (transactionType) {
case DEPOSIT: private static EnumOptionData depositType(DepositAccountTransactionType transactionType) {
optionData=new EnumOptionData(DepositAccountTransactionType.DEPOSIT.getValue().longValue(), DepositAccountTransactionType.DEPOSIT.getCode(), "Deposit");
break; EnumOptionData optionData = null;
switch (transactionType) {
case WITHDRAW: case DEPOSIT:
optionData=new EnumOptionData(DepositAccountTransactionType.WITHDRAW.getValue().longValue(), DepositAccountTransactionType.WITHDRAW.getCode(), "Withdraw"); optionData = new EnumOptionData(DepositAccountTransactionType.DEPOSIT.getValue().longValue(),
break; DepositAccountTransactionType.DEPOSIT.getCode(), "Deposit");
break;
case REVERSAL:
optionData=new EnumOptionData(DepositAccountTransactionType.REVERSAL.getValue().longValue(), DepositAccountTransactionType.REVERSAL.getCode(), "Revarsal"); case WITHDRAW:
break; optionData = new EnumOptionData(DepositAccountTransactionType.WITHDRAW.getValue().longValue(),
default: DepositAccountTransactionType.WITHDRAW.getCode(), "Withdraw");
optionData=new EnumOptionData(DepositAccountTransactionType.INVALID.getValue().longValue(), DepositAccountTransactionType.INVALID.getCode(), "Invalid Transaction"); break;
break;
} case REVERSAL:
return optionData; optionData = new EnumOptionData(DepositAccountTransactionType.REVERSAL.getValue().longValue(),
} DepositAccountTransactionType.REVERSAL.getCode(), "Revarsal");
break;
default:
optionData = new EnumOptionData(DepositAccountTransactionType.INVALID.getValue().longValue(),
DepositAccountTransactionType.INVALID.getCode(), "Invalid Transaction");
break;
}
return optionData;
}
} }
@@ -52,7 +52,7 @@ public interface DepositAccountWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'RENEW_DEPOSITACCOUNT')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'RENEW_DEPOSITACCOUNT')")
EntityIdentifier renewDepositAccount(DepositAccountCommand command); EntityIdentifier renewDepositAccount(DepositAccountCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER')")
EntityIdentifier postInterestToDepositAccount(Collection<DepositAccountsForLookup> accounts); EntityIdentifier postInterestToDepositAccount(Collection<DepositAccountsForLookup> accounts);
} }
@@ -305,9 +305,10 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
"deposit.transaction.canot.withdraw.before.lockinperiod.reached", "deposit.transaction.canot.withdraw.before.lockinperiod.reached",
"You can not withdraw your application before maturity date reached"); } "You can not withdraw your application before maturity date reached"); }
} }
// if (eventDate.isBefore(account.maturesOnDate())) { // if (eventDate.isBefore(account.maturesOnDate())) {
// this.depositAccountAssembler.adjustTotalAmountForPreclosureInterest(account, eventDate); // this.depositAccountAssembler.adjustTotalAmountForPreclosureInterest(account,
// } // eventDate);
// }
account.withdrawDepositAccountMoney(defaultDepositLifecycleStateMachine(), fixedTermDepositInterestCalculator, eventDate); account.withdrawDepositAccountMoney(defaultDepositLifecycleStateMachine(), fixedTermDepositInterestCalculator, eventDate);
this.depositAccountRepository.save(account); this.depositAccountRepository.save(account);
String noteText = command.getNote(); String noteText = command.getNote();
@@ -421,26 +422,23 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
return new EntityIdentifier(Long.valueOf(-1)); return new EntityIdentifier(Long.valueOf(-1));
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier postInterestToDepositAccount(Collection<DepositAccountsForLookup> accounts) { public EntityIdentifier postInterestToDepositAccount(Collection<DepositAccountsForLookup> accounts) {
try { try {
for (DepositAccountsForLookup accountData : accounts) for (DepositAccountsForLookup accountData : accounts) {
{ DepositAccount account = this.depositAccountRepository.findOne(accountData.getId());
DepositAccount account = this.depositAccountRepository.findOne(accountData.getId()); if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(accountData.getId()); }
if (account == null || account.isDeleted()) { this.depositAccountAssembler.postInterest(account);
throw new DepositAccountNotFoundException(accountData.getId()); this.depositAccountRepository.save(account);
} }
this.depositAccountAssembler.postInterest(account); return new EntityIdentifier(new Long(accounts.size()));
this.depositAccountRepository.save(account); } catch (Exception e) {
} return new EntityIdentifier(Long.valueOf(-1));
return new EntityIdentifier(new Long(accounts.size())); }
} catch (Exception e) {
return new EntityIdentifier(Long.valueOf(-1)); }
}
}
} }
@@ -9,24 +9,22 @@ import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidation
import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositStateTransitionCommand; import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositStateTransitionCommand;
public class DepositStateTransitionCommandValidator { public class DepositStateTransitionCommandValidator {
private final DepositStateTransitionCommand command;
public DepositStateTransitionCommandValidator(final DepositStateTransitionCommand command) {
this.command=command;
}
public void validate(){
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transition");
baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero();
baseDataValidator.reset().parameter("eventDate").value(command.getEventDate()).notNull();
baseDataValidator.reset().parameter("note").value(command.getNote()).notNull();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
}
private final DepositStateTransitionCommand command;
public DepositStateTransitionCommandValidator(final DepositStateTransitionCommand command) {
this.command = command;
}
public void validate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transition");
baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero();
baseDataValidator.reset().parameter("eventDate").value(command.getEventDate()).notNull();
baseDataValidator.reset().parameter("note").value(command.getNote()).notNull();
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); }
}
} }
@@ -9,35 +9,38 @@ import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidation
import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositAccountCommand; import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositAccountCommand;
public class RenewDepositAccountCommandValidator { public class RenewDepositAccountCommandValidator {
private final DepositAccountCommand command;
public RenewDepositAccountCommandValidator(final DepositAccountCommand command) {
this.command=command;
}
public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account");
baseDataValidator.reset().parameter("clientId").value(command.getClientId()).ignoreIfNull();
baseDataValidator.reset().parameter("productId").value(command.getProductId()).ignoreIfNull();
baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100);
baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().zeroOrPositiveAmount(); private final DepositAccountCommand command;
baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); public RenewDepositAccountCommandValidator(final DepositAccountCommand command) {
baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().integerGreaterThanZero(); this.command = command;
}
baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull().integerGreaterThanZero();
baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()).ignoreIfNull().inMinMaxRange(2, 2); public void validateForCreate() {
baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).ignoreIfNull();
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account");
}
} baseDataValidator.reset().parameter("clientId").value(command.getClientId()).ignoreIfNull();
baseDataValidator.reset().parameter("productId").value(command.getProductId()).ignoreIfNull();
baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100);
baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull()
.zeroOrPositiveAmount();
baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).ignoreIfNull()
.zeroOrPositiveAmount();
baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().integerGreaterThanZero();
baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull()
.integerGreaterThanZero();
baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType())
.ignoreIfNull().inMinMaxRange(2, 2);
baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).ignoreIfNull();
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); }
}
} }
@@ -43,7 +43,7 @@ import org.springframework.stereotype.Component;
public class DepositProductsApiResource { public class DepositProductsApiResource {
private final String entityType = "DEPOSITPRODUCT"; private final String entityType = "DEPOSITPRODUCT";
@Autowired @Autowired
private DepositProductReadPlatformService depositProductReadPlatformService; private DepositProductReadPlatformService depositProductReadPlatformService;