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,
@@ -40,133 +40,134 @@ import org.springframework.stereotype.Component;
@Scope("singleton") @Scope("singleton")
public class SavingsAccountApiResource { public class SavingsAccountApiResource {
@Autowired @Autowired
private SavingAccountWritePlatformService savingAccountWritePlatformService; private SavingAccountWritePlatformService savingAccountWritePlatformService;
@Autowired @Autowired
private SavingAccountReadPlatformService savingAccountReadPlatformService; private SavingAccountReadPlatformService savingAccountReadPlatformService;
@Autowired @Autowired
private PortfolioApiDataConversionService apiDataConversionService; private PortfolioApiDataConversionService apiDataConversionService;
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "SAVINGSACCOUNT"; private final String entityType = "SAVINGSACCOUNT";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
@Autowired @Autowired
private CalculateSavingSchedule calculateSavingSchedule; private CalculateSavingSchedule calculateSavingSchedule;
private static final Set<String> typicalResponseParameters = new HashSet<String>( private static final Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "status", "externalId",
Arrays.asList("id", "status", "externalId", "clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod", "savingsFrequencyType", "clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod",
"totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType", "interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", "savingsFrequencyType", "totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType",
"actualCommencementDate", "maturesOnDate", "projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount", "preClosureAllowed", "interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", "actualCommencementDate", "maturesOnDate",
"preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType")); "projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount",
"preClosureAllowed", "preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", "isLockinPeriodAllowed",
"lockinPeriod", "lockinPeriodType"));
@POST @POST
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String createSavingAccount(@QueryParam("command") final String commandParam, public String createSavingAccount(@QueryParam("command") final String commandParam, @Context final UriInfo uriInfo,
@Context final UriInfo uriInfo,final String jsonRequestBody){ final String jsonRequestBody) {
final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(null, jsonRequestBody); final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(null, jsonRequestBody);
if (is(commandParam, "calculateSavingSchedule")) { 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); EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.createSavingAccount(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(entityIdentifier); return this.apiJsonSerializerService.serializeEntityIdentifier(entityIdentifier);
} }
private String calculateSavingSchedule(final UriInfo uriInfo, final CalculateSavingScheduleCommand command) { private String calculateSavingSchedule(final UriInfo uriInfo, final CalculateSavingScheduleCommand command) {
SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command); SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serializeSavingScheduleDataToJson(prettyPrint, responseParameters, savingScheduleData); return this.apiJsonSerializerService.serializeSavingScheduleDataToJson(prettyPrint, responseParameters, savingScheduleData);
} }
@PUT @PUT
@Path("{accountId}") @Path("{accountId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public Response updateSavingAccount(@PathParam("accountId") final Long accountId,final String jsonRequestBody){ public Response updateSavingAccount(@PathParam("accountId") final Long accountId, final String jsonRequestBody) {
final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(accountId, jsonRequestBody); final SavingAccountCommand command = this.apiDataConversionService.convertJsonToSavingAccountCommand(accountId, jsonRequestBody);
EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.updateSavingAccount(command); EntityIdentifier entityIdentifier = this.savingAccountWritePlatformService.updateSavingAccount(command);
return Response.ok().entity(entityIdentifier).build(); return Response.ok().entity(entityIdentifier).build();
} }
@GET @GET
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveAllDepositAccounts(@Context final UriInfo uriInfo) { public String retrieveAllDepositAccounts(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters); responseParameters.addAll(typicalResponseParameters);
} }
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<SavingAccountData> accounts = this.savingAccountReadPlatformService.retrieveAllSavingsAccounts(); Collection<SavingAccountData> accounts = this.savingAccountReadPlatformService.retrieveAllSavingsAccounts();
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, accounts); return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, accounts);
} }
@GET @GET
@Path("{accountId}") @Path("{accountId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveDepositAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) { public String retrieveDepositAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters); responseParameters.addAll(typicalResponseParameters);
} }
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingAccountData account = this.savingAccountReadPlatformService.retrieveSavingsAccount(accountId); SavingAccountData account = this.savingAccountReadPlatformService.retrieveSavingsAccount(accountId);
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account); return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account);
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@GET @GET
@Path("template") @Path("template")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveNewDepositAccountDetails( public String retrieveNewDepositAccountDetails(@QueryParam("clientId") final Long clientId,
@QueryParam("clientId") final Long clientId, @QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) {
@QueryParam("productId") final Long productId,
@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters); responseParameters.addAll(typicalResponseParameters);
} }
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingAccountData account = null; SavingAccountData account = null;
// this.savingAccountReadPlatformService.retrieveNewSavingsAccountDetails(clientId, productId); // this.savingAccountReadPlatformService.retrieveNewSavingsAccountDetails(clientId,
// productId);
return this.apiJsonSerializerService.serializeSavingAccountsDataToJson(prettyPrint, responseParameters, account); 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, public CalculateSavingScheduleCommand(final Long productId, final BigDecimal deposit, final Integer payEvery,
final BigDecimal deposit, final Integer paymentFrequencyType, final BigDecimal interestRate, final LocalDate paymentsStartingFromDate,
final Integer payEvery, final Integer tenure) {
final Integer paymentFrequencyType,
final BigDecimal interestRate,
final LocalDate paymentsStartingFromDate,
final Integer tenure) {
this.productId = productId; this.productId = productId;
this.deposit = deposit; this.deposit = deposit;
this.payEvery = payEvery; this.payEvery = payEvery;
this.paymentFrequencyType=paymentFrequencyType; this.paymentFrequencyType = paymentFrequencyType;
this.interestRate= interestRate; this.interestRate = interestRate;
this.paymentsStartingFromDate=paymentsStartingFromDate; this.paymentsStartingFromDate = paymentsStartingFromDate;
this.tenure = tenure; this.tenure = tenure;
} }
public Long getProductId() { public Long getProductId() {
return this.productId; return this.productId;
} }
public BigDecimal getDeposit() { public BigDecimal getDeposit() {
return this.deposit; return this.deposit;
} }
public Integer getPayEvery() { public Integer getPayEvery() {
return this.payEvery; return this.payEvery;
} }
public Integer getPaymentFrequencyType() { public Integer getPaymentFrequencyType() {
return this.paymentFrequencyType; return this.paymentFrequencyType;
} }
public BigDecimal getInterestRate() { public BigDecimal getInterestRate() {
return this.interestRate; return this.interestRate;
} }
public LocalDate getPaymentsStartingFromDate() { public LocalDate getPaymentsStartingFromDate() {
return this.paymentsStartingFromDate; return this.paymentsStartingFromDate;
} }
public Integer getTenure() { public Integer getTenure() {
return this.tenure; return this.tenure;
} }
} }
@@ -7,244 +7,238 @@ 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 Long id; private final String currencyCode;
private final Long clientId; private final Integer digitsAfterDecimal;
private final Long productId; private final BigDecimal savingsDepositAmount;
private final String externalId; private final BigDecimal recurringInterestRate;
private final BigDecimal savingInterestRate;
private final Integer tenure;
private final String currencyCode; private final boolean isLockinPeriodAllowed;
private final Integer digitsAfterDecimal; private final Integer lockinPeriod;
private final BigDecimal savingsDepositAmount; private final Integer lockinPeriodType;
private final BigDecimal recurringInterestRate;
private final BigDecimal savingInterestRate;
private final Integer tenure;
private final boolean isLockinPeriodAllowed; private final LocalDate commencementDate;
private final Integer lockinPeriod; private final Integer savingProductType;
private final Integer lockinPeriodType; private final Integer tenureType;
private final Integer frequency;
private final Integer interestType;
private final LocalDate commencementDate; private final Integer interestCalculationMethod;
private final Integer savingProductType; private final BigDecimal minimumBalanceForWithdrawal;
private final Integer tenureType; private final boolean isPartialDepositAllowed;
private final Integer frequency; private final Integer payEvery;
private final Integer interestType;
private final Integer interestCalculationMethod; private final Set<String> modifiedParameters;
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;
public SavingAccountCommand(final Set<String> modifiedParameters, this.currencyCode = currencyCode;
final Long id, this.digitsAfterDecimal = digitsAfterDecimal;
final Long clientId, this.savingsDepositAmount = savingsDepositAmount;
final Long productId, this.recurringInterestRate = recurringInterestRate;
final String externalId,final String currencyCode, final Integer digitsAfterDecimal, this.savingInterestRate = savingInterestRate;
final BigDecimal savingsDepositAmount, this.tenure = tenure;
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.modifiedParameters = modifiedParameters;
this.digitsAfterDecimal = digitsAfterDecimal; this.commencementDate = commencementDate;
this.savingsDepositAmount = savingsDepositAmount;
this.recurringInterestRate = recurringInterestRate;
this.savingInterestRate = savingInterestRate;
this.tenure = tenure;
this.modifiedParameters = modifiedParameters; this.savingProductType = savingProductType;
this.commencementDate = commencementDate; this.tenureType = tenureType;
this.frequency = frequency;
this.interestType = interestType;
this.isPartialDepositAllowed = isPartialDepositAllowed;
this.savingProductType=savingProductType; this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.tenureType=tenureType; this.lockinPeriod = lockInPeriod;
this.frequency=frequency; this.lockinPeriodType = lockinPeriodType;
this.interestType=interestType; this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.isPartialDepositAllowed=isPartialDepositAllowed; this.interestCalculationMethod = interestCalculationMethod;
this.payEvery = payEvery;
}
public Long getId() {
return id;
}
this.isLockinPeriodAllowed = isLockinPeriodAllowed; public Long getClientId() {
this.lockinPeriod = lockInPeriod; return clientId;
this.lockinPeriodType = lockinPeriodType; }
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal;
this.interestCalculationMethod=interestCalculationMethod;
this.payEvery = payEvery;
}
public Long getId() { public Long getProductId() {
return id; return productId;
} }
public Long getClientId() { public String getExternalId() {
return clientId; return externalId;
} }
public Long getProductId() { public String getCurrencyCode() {
return productId; return currencyCode;
} }
public String getExternalId() { public Integer getDigitsAfterDecimal() {
return externalId; return digitsAfterDecimal;
} }
public String getCurrencyCode() { public BigDecimal getSavingsDepositAmount() {
return currencyCode; return savingsDepositAmount;
} }
public Integer getDigitsAfterDecimal() { public BigDecimal getRecurringInterestRate() {
return digitsAfterDecimal; return recurringInterestRate;
} }
public BigDecimal getSavingsDepositAmount() { public BigDecimal getSavingInterestRate() {
return savingsDepositAmount; return savingInterestRate;
} }
public BigDecimal getRecurringInterestRate() { public Integer getTenure() {
return recurringInterestRate; return tenure;
} }
public BigDecimal getSavingInterestRate() { public boolean isLockinPeriodAllowed() {
return savingInterestRate; return isLockinPeriodAllowed;
} }
public Integer getTenure() { public Integer getLockinPeriod() {
return tenure; return lockinPeriod;
} }
public boolean isLockinPeriodAllowed() { public Integer getLockinPeriodType() {
return isLockinPeriodAllowed; return lockinPeriodType;
} }
public Integer getLockinPeriod() { public LocalDate getCommencementDate() {
return lockinPeriod; return commencementDate;
} }
public Integer getLockinPeriodType() { public Integer getSavingProductType() {
return lockinPeriodType; return savingProductType;
} }
public LocalDate getCommencementDate() { public Integer getTenureType() {
return commencementDate; return tenureType;
} }
public Integer getSavingProductType() { public Integer getFrequency() {
return savingProductType; return frequency;
} }
public Integer getTenureType() { public Integer getInterestType() {
return tenureType; return interestType;
} }
public Integer getFrequency() { public Integer getInterestCalculationMethod() {
return frequency; return interestCalculationMethod;
} }
public Integer getInterestType() { public BigDecimal getMinimumBalanceForWithdrawal() {
return interestType; return minimumBalanceForWithdrawal;
} }
public Integer getInterestCalculationMethod() { public boolean isPartialDepositAllowed() {
return interestCalculationMethod; return isPartialDepositAllowed;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public Integer getPayEvery() {
return minimumBalanceForWithdrawal; return this.payEvery;
} }
public boolean isPartialDepositAllowed() { public boolean isNoFieldChanged() {
return isPartialDepositAllowed; return this.modifiedParameters.isEmpty();
} }
public Integer getPayEvery() { public boolean isProductIdChanged() {
return this.payEvery; return this.modifiedParameters.contains("productId");
} }
public boolean isNoFieldChanged() { public boolean isExternalIdChanged() {
return this.modifiedParameters.isEmpty(); return this.modifiedParameters.contains("externalId");
} }
public boolean isProductIdChanged(){ public boolean isDepositAmountChanged() {
return this.modifiedParameters.contains("productId"); return this.modifiedParameters.contains("deposit");
} }
public boolean isExternalIdChanged(){ public boolean isTenureInMonthsChanged() {
return this.modifiedParameters.contains("externalId"); return this.modifiedParameters.contains("tenureInMonths");
} }
public boolean isDepositAmountChanged(){ public boolean isLockinPeriodChanged() {
return this.modifiedParameters.contains("deposit"); return this.modifiedParameters.contains("lockinPeriod");
} }
public boolean isTenureInMonthsChanged() { public boolean isPreClosureInterestRateChanged() {
return this.modifiedParameters.contains("tenureInMonths"); return this.modifiedParameters.contains("preClosureInterestRate");
} }
public boolean isLockinPeriodChanged() { public boolean isPreClosureAllowedChanged() {
return this.modifiedParameters.contains("lockinPeriod"); return this.modifiedParameters.contains("preClosureAllowed");
} }
public boolean isPreClosureInterestRateChanged(){ public boolean isCommencementDateChanged() {
return this.modifiedParameters.contains("preClosureInterestRate"); return this.modifiedParameters.contains("commencementDate");
} }
public boolean isPreClosureAllowedChanged() { public boolean isTenureTypeEnumChanged() {
return this.modifiedParameters.contains("preClosureAllowed"); return this.modifiedParameters.contains("tenureType");
} }
public boolean isCommencementDateChanged() { public boolean isSavingProductTypeChanged() {
return this.modifiedParameters.contains("commencementDate"); return this.modifiedParameters.contains("savingProductType");
} }
public boolean isTenureTypeEnumChanged() { public boolean isSavingFrequencyTypeChanged() {
return this.modifiedParameters.contains("tenureType"); return this.modifiedParameters.contains("frequency");
} }
public boolean isSavingProductTypeChanged() { public boolean isSavingInterestCalculationMethodChanged() {
return this.modifiedParameters.contains("savingProductType"); return this.modifiedParameters.contains("interestCalculationMethod");
} }
public boolean isSavingFrequencyTypeChanged() { public boolean isReccuringInterestRateChanged() {
return this.modifiedParameters.contains("frequency"); return this.modifiedParameters.contains("recurringInterestRate");
} }
public boolean isSavingInterestCalculationMethodChanged() { public boolean isSavingInterestRateChanged() {
return this.modifiedParameters.contains("interestCalculationMethod"); return this.modifiedParameters.contains("savingInterestRate");
} }
public boolean isReccuringInterestRateChanged() { public boolean isLockinPeriodAllowedChanged() {
return this.modifiedParameters.contains("recurringInterestRate"); return this.modifiedParameters.contains("isLockinPeriodAllowed");
} }
public boolean isSavingInterestRateChanged() { public boolean isLockinPeriodTypeChanged() {
return this.modifiedParameters.contains("savingInterestRate"); return this.modifiedParameters.contains("lockinPeriodType");
} }
public boolean isLockinPeriodAllowedChanged() { public boolean isPartialDepositAllowedChanged() {
return this.modifiedParameters.contains("isLockinPeriodAllowed"); return this.modifiedParameters.contains("isPartialDepositAllowed");
} }
public boolean isLockinPeriodTypeChanged() { public boolean isPayEveryChanged() {
return this.modifiedParameters.contains("lockinPeriodType"); return this.modifiedParameters.contains("payEvery");
} }
public boolean isPartialDepositAllowedChanged() { public CalculateSavingScheduleCommand toCalculateSavingScheduleCommand() {
return this.modifiedParameters.contains("isPartialDepositAllowed"); return new CalculateSavingScheduleCommand(productId, savingsDepositAmount, payEvery, frequency, recurringInterestRate,
} commencementDate, tenure);
}
public boolean isPayEveryChanged(){
return this.modifiedParameters.contains("payEvery");
}
public CalculateSavingScheduleCommand toCalculateSavingScheduleCommand() {
return new CalculateSavingScheduleCommand(productId, savingsDepositAmount, payEvery, frequency, recurringInterestRate, commencementDate,tenure);
}
} }
@@ -7,28 +7,28 @@ import org.mifosplatform.organisation.monetary.data.CurrencyData;
public class SavingScheduleData { public class SavingScheduleData {
private final CurrencyData currency; private final CurrencyData currency;
private final BigDecimal cumulativeDepositDue; private final BigDecimal cumulativeDepositDue;
private final Collection<SavingSchedulePeriodData> periods; private final Collection<SavingSchedulePeriodData> periods;
public SavingScheduleData(final CurrencyData currency, final BigDecimal cumulativeDepositDue, public SavingScheduleData(final CurrencyData currency, final BigDecimal cumulativeDepositDue,
final Collection<SavingSchedulePeriodData> periods) { final Collection<SavingSchedulePeriodData> periods) {
this.currency = currency; this.currency = currency;
this.cumulativeDepositDue= cumulativeDepositDue; this.cumulativeDepositDue = cumulativeDepositDue;
this.periods= periods; this.periods = periods;
} }
public CurrencyData getCurrency() { public CurrencyData getCurrency() {
return this.currency; return this.currency;
} }
public BigDecimal getCumulativeDepositDue() { public BigDecimal getCumulativeDepositDue() {
return this.cumulativeDepositDue; return this.cumulativeDepositDue;
} }
public Collection<SavingSchedulePeriodData> getPeriods() { public Collection<SavingSchedulePeriodData> getPeriods() {
return this.periods; return this.periods;
} }
} }
@@ -6,36 +6,37 @@ import org.joda.time.LocalDate;
public class SavingSchedulePeriodData { public class SavingSchedulePeriodData {
private final Integer period; private final Integer period;
private final LocalDate dueDate; private final LocalDate dueDate;
private final BigDecimal depositDue; private final BigDecimal depositDue;
private final BigDecimal depositPaid; private final BigDecimal depositPaid;
public SavingSchedulePeriodData(final Integer period, final LocalDate dueDate, final BigDecimal depositDue, final BigDecimal depositPaid) { public SavingSchedulePeriodData(final Integer period, final LocalDate dueDate, final BigDecimal depositDue, final BigDecimal depositPaid) {
this.period = period; this.period = period;
this.dueDate = dueDate; this.dueDate = dueDate;
this.depositDue= depositDue; this.depositDue = depositDue;
this.depositPaid= depositPaid; this.depositPaid = depositPaid;
} }
public static SavingSchedulePeriodData addScheduleInformation(int periodNumber, LocalDate scheduleDate, BigDecimal depositAmountPerPeriod){ public static SavingSchedulePeriodData addScheduleInformation(int periodNumber, LocalDate scheduleDate,
return new SavingSchedulePeriodData(periodNumber, scheduleDate, depositAmountPerPeriod, BigDecimal.ZERO); BigDecimal depositAmountPerPeriod) {
} return new SavingSchedulePeriodData(periodNumber, scheduleDate, depositAmountPerPeriod, BigDecimal.ZERO);
}
public Integer getPeriod() { public Integer getPeriod() {
return this.period; return this.period;
} }
public LocalDate getDueDate() { public LocalDate getDueDate() {
return this.dueDate; return this.dueDate;
} }
public BigDecimal getDepositDue() { public BigDecimal getDepositDue() {
return this.depositDue; return this.depositDue;
} }
public BigDecimal getDepositPaid() { public BigDecimal getDepositPaid() {
return this.depositPaid; return this.depositPaid;
} }
} }
@@ -7,6 +7,5 @@ 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 @ManyToOne
@JoinColumn(name = "client_id", nullable = false) @JoinColumn(name = "client_id", nullable = false)
private Client client; private Client client;
@ManyToOne @ManyToOne
@JoinColumn(name = "product_id") @JoinColumn(name = "product_id")
private SavingProduct product; private SavingProduct product;
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType; // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
@Column(name = "savings_product_type", nullable=false) // Integer e.g. private Integer savingProductType;
private SavingProductType savingProductType; @Column(name = "savings_product_type", nullable = false)
private SavingProductType savingProductType;
@Column(name = "external_id") @Column(name = "external_id")
private String externalId; private String externalId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Embedded @Embedded
private MonetaryCurrency currency; private MonetaryCurrency currency;
@Column(name = "deposit_amount_per_period", scale = 6, precision = 19, nullable = false) @Column(name = "deposit_amount_per_period", scale = 6, precision = 19, nullable = false)
private BigDecimal savingsDepositAmountPerPeriod; private BigDecimal savingsDepositAmountPerPeriod;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Column(name = "total_deposit_amount", scale = 6, precision = 19, nullable = false) @Column(name = "total_deposit_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal totalSavingsAmount; private BigDecimal totalSavingsAmount;
@Column(name = "reccuring_nominal_interest_rate", scale = 6, precision = 19, nullable = false) @Column(name = "reccuring_nominal_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal reccuringInterestRate; private BigDecimal reccuringInterestRate;
@Column(name = "regular_saving_nominal_interest_rate", scale = 6, precision = 19, nullable = false) @Column(name = "regular_saving_nominal_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal savingInterestRate; private BigDecimal savingInterestRate;
@Column(name = "tenure", nullable=false) @Column(name = "tenure", nullable = false)
private Integer tenure; private Integer tenure;
@Column(name = "tenure_type", nullable=false) @Column(name = "tenure_type", nullable = false)
private TenureTypeEnum tenureType; private TenureTypeEnum tenureType;
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType; // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
@Column(name = "frequency", nullable=false) // Integer e.g. private Integer savingProductType;
private SavingFrequencyType frequency; @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) // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
private SavingsInterestType interestType; // Integer e.g. private Integer savingProductType;
@Column(name = "interest_type", nullable = false)
// FIXME - MADHUKAR - Do not use the actual enum type here but instead use Integer e.g. private Integer savingProductType; private SavingsInterestType interestType;
@Column(name = "interest_calculation_method")
private SavingInterestCalculationMethod interestCalculationMethod; // FIXME - MADHUKAR - Do not use the actual enum type here but instead use
// Integer e.g. private Integer savingProductType;
@Temporal(TemporalType.DATE) @Column(name = "interest_calculation_method")
@Column(name = "projected_commencement_date") private SavingInterestCalculationMethod interestCalculationMethod;
private Date projectedCommencementDate;
@Temporal(TemporalType.DATE)
@SuppressWarnings("unused") @Column(name = "projected_commencement_date")
@Temporal(TemporalType.DATE) private Date projectedCommencementDate;
@Column(name = "actual_commencement_date")
private Date actualCommencementDate; @SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@SuppressWarnings("unused") @Column(name = "actual_commencement_date")
@Temporal(TemporalType.DATE) private Date actualCommencementDate;
@Column(name = "matures_on_date")
private Date maturesOnDate; @SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@SuppressWarnings("unused") @Column(name = "matures_on_date")
@Column(name = "projected_interest_accrued_on_maturity", scale = 6, precision = 19, nullable = false) private Date maturesOnDate;
private BigDecimal projectedInterestAccruedOnMaturity;
@SuppressWarnings("unused")
@SuppressWarnings("unused") @Column(name = "projected_interest_accrued_on_maturity", scale = 6, precision = 19, nullable = false)
@Column(name = "actual_interest_accrued", scale = 6, precision = 19, nullable = false) private BigDecimal projectedInterestAccruedOnMaturity;
private BigDecimal interestAccrued;
@SuppressWarnings("unused")
@SuppressWarnings("unused") @Column(name = "actual_interest_accrued", scale = 6, precision = 19, nullable = false)
@Column(name = "projected_total_maturity_amount", scale = 6, precision = 19, nullable = false) private BigDecimal interestAccrued;
private BigDecimal projectedTotalOnMaturity;
@SuppressWarnings("unused")
@SuppressWarnings("unused") @Column(name = "projected_total_maturity_amount", scale = 6, precision = 19, nullable = false)
@Column(name = "actual_total_amount", scale = 6, precision = 19, nullable = false) private BigDecimal projectedTotalOnMaturity;
private BigDecimal total;
@SuppressWarnings("unused")
@Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false) @Column(name = "actual_total_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal preClosureInterestRate; private BigDecimal total;
@Column(name = "is_preclosure_allowed", nullable = false) @Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false)
private boolean preClosureAllowed = false; private BigDecimal preClosureInterestRate;
@Column(name = "is_deleted", nullable=false) @Column(name = "is_preclosure_allowed", nullable = false)
private boolean deleted = false; private boolean preClosureAllowed = false;
@Column(name = "status_enum", nullable = false) @Column(name = "is_deleted", nullable = false)
private Integer accountStatus; private boolean deleted = false;
@SuppressWarnings("unused") @Column(name = "status_enum", nullable = false)
@Temporal(TemporalType.DATE) private Integer accountStatus;
@Column(name = "closedon_date")
private Date closedOnDate; @SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@SuppressWarnings("unused") @Column(name = "closedon_date")
@Temporal(TemporalType.DATE) private Date closedOnDate;
@Column(name = "rejectedon_date")
private Date rejectedOnDate; @SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Temporal(TemporalType.DATE) @Column(name = "rejectedon_date")
@Column(name = "withdrawnon_date") private Date rejectedOnDate;
private Date withdrawnOnDate;
@Temporal(TemporalType.DATE)
@Column(name = "is_lock_in_period_allowed", nullable=false) @Column(name = "withdrawnon_date")
private boolean isLockinPeriodAllowed = false; private Date withdrawnOnDate;
@Column(name = "lock_in_period", nullable=false) @Column(name = "is_lock_in_period_allowed", nullable = false)
private Integer lockinPeriod; private boolean isLockinPeriodAllowed = false;
@Column(name = "lock_in_period_type", nullable=false) @Column(name = "lock_in_period", nullable = false)
private PeriodFrequencyType lockinPeriodType; private Integer lockinPeriod;
// see @Column(name = "lock_in_period_type", nullable = false)
// http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags private PeriodFrequencyType lockinPeriodType;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "savingAccount", orphanRemoval = true) // see
private final List<SavingScheduleInstallments> savingScheduleInstallments = new ArrayList<SavingScheduleInstallments>(); // http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "savingAccount", orphanRemoval = true)
public static SavingAccount openNew( private final List<SavingScheduleInstallments> savingScheduleInstallments = new ArrayList<SavingScheduleInstallments>();
Client client,
SavingProduct product, public static SavingAccount openNew(Client client, SavingProduct product, String externalId, Money savingsDeposit,
String externalId, BigDecimal reccuringInterestRate, BigDecimal savingInterestRate, Integer tenure, LocalDate commencementDate,
Money savingsDeposit, TenureTypeEnum tenureTypeEnum, SavingProductType savingProductType, SavingFrequencyType savingFrequencyType,
BigDecimal reccuringInterestRate, SavingsInterestType interestType, SavingInterestCalculationMethod savingInterestCalculationMethod,
BigDecimal savingInterestRate, boolean isLockinPeriodAllowed, Integer lockinPeriod, PeriodFrequencyType lockinPeriodType,
Integer tenure, ReccuringDepositInterestCalculator reccuringDepositInterestCalculator, final DepositLifecycleStateMachine lifecycleStateMachine) {
LocalDate commencementDate,
TenureTypeEnum tenureTypeEnum, Money futureValueOnMaturity = null;
SavingProductType savingProductType, if (savingProductType.isReccuring()) {
SavingFrequencyType savingFrequencyType, futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
SavingsInterestType interestType, reccuringInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
SavingInterestCalculationMethod savingInterestCalculationMethod, } else if (savingProductType.isRegular()) {
boolean isLockinPeriodAllowed, futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
Integer lockinPeriod, savingInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
PeriodFrequencyType lockinPeriodType, }
ReccuringDepositInterestCalculator reccuringDepositInterestCalculator,
final DepositLifecycleStateMachine lifecycleStateMachine) { return new SavingAccount(client, externalId, product, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure,
commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, interestType, savingInterestCalculationMethod,
Money futureValueOnMaturity = null; isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, futureValueOnMaturity, lifecycleStateMachine);
if(savingProductType.isReccuring()){ }
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, reccuringInterestRate,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod); public SavingAccount(Client client, String externalId, SavingProduct product, Money savingsDeposit, BigDecimal reccuringInterestRate,
} else if(savingProductType.isRegular()){ BigDecimal savingInterestRate, Integer tenure, LocalDate commencementDate, TenureTypeEnum tenureTypeEnum,
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, savingInterestRate, SavingProductType savingProductType, SavingFrequencyType savingFrequencyType, SavingsInterestType interestType,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod); SavingInterestCalculationMethod savingInterestCalculationMethod, boolean isLockinPeriodAllowed, Integer lockinPeriod,
} PeriodFrequencyType lockinPeriodType, Money futureValueOnMaturity, final DepositLifecycleStateMachine lifecycleStateMachine) {
return new SavingAccount(client, externalId, product, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure, DepositAccountStatus from = null;
commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, interestType, savingInterestCalculationMethod, if (accountStatus != null) {
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, futureValueOnMaturity, lifecycleStateMachine); from = DepositAccountStatus.fromInt(accountStatus);
} }
public SavingAccount(Client client, String externalId, DepositAccountStatus statusEnum = lifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CREATED, from);
SavingProduct product, Money savingsDeposit, accountStatus = statusEnum.getValue();
BigDecimal reccuringInterestRate, BigDecimal savingInterestRate,
Integer tenure, LocalDate commencementDate, this.total = BigDecimal.ZERO;
TenureTypeEnum tenureTypeEnum, this.preClosureInterestRate = BigDecimal.ZERO;
SavingProductType savingProductType, this.totalSavingsAmount = BigDecimal.ZERO;
SavingFrequencyType savingFrequencyType, SavingsInterestType interestType, this.interestAccrued = BigDecimal.ZERO;
SavingInterestCalculationMethod savingInterestCalculationMethod,
boolean isLockinPeriodAllowed, Integer lockinPeriod, this.client = client;
PeriodFrequencyType lockinPeriodType, Money futureValueOnMaturity, this.externalId = externalId;
final DepositLifecycleStateMachine lifecycleStateMachine) { this.product = product;
this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount();
DepositAccountStatus from = null; this.currency = savingsDeposit.getCurrency();
if (accountStatus != null) { this.reccuringInterestRate = reccuringInterestRate;
from = DepositAccountStatus.fromInt(accountStatus); this.savingInterestRate = savingInterestRate;
} this.tenure = tenure;
this.projectedCommencementDate = commencementDate.toDate();
DepositAccountStatus statusEnum = lifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CREATED, from); this.tenureType = tenureTypeEnum;
accountStatus = statusEnum.getValue(); this.savingProductType = savingProductType;
this.frequency = savingFrequencyType;
this.total=BigDecimal.ZERO; this.interestType = interestType;
this.preClosureInterestRate=BigDecimal.ZERO; this.interestCalculationMethod = savingInterestCalculationMethod;
this.totalSavingsAmount = BigDecimal.ZERO; this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.interestAccrued = BigDecimal.ZERO; this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
this.client = client; this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.externalId = externalId; this.projectedInterestAccruedOnMaturity = futureValueOnMaturity.getAmount().subtract(
this.product = product; BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue() * tenure.doubleValue()));
this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount(); }
this.currency = savingsDeposit.getCurrency();
this.reccuringInterestRate = reccuringInterestRate; public void modifyAccount(SavingProduct product, String externalId, Money savingsDeposit, BigDecimal reccuringInterestRate,
this.savingInterestRate = savingInterestRate; BigDecimal savingInterestRate, Integer tenure, LocalDate commencementDate, TenureTypeEnum tenureTypeEnum,
this.tenure =tenure; SavingProductType savingProductType, SavingFrequencyType savingFrequencyType,
this.projectedCommencementDate=commencementDate.toDate(); SavingInterestCalculationMethod savingInterestCalculationMethod, boolean isLockinPeriodAllowed, Integer lockinPeriod,
this.tenureType = tenureTypeEnum; PeriodFrequencyType lockinPeriodType, ReccuringDepositInterestCalculator reccuringDepositInterestCalculator) {
this.savingProductType = savingProductType;
this.frequency = savingFrequencyType; Money futureValueOnMaturity = null;
this.interestType = interestType; if (savingProductType.isReccuring()) {
this.interestCalculationMethod= savingInterestCalculationMethod; futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
this.isLockinPeriodAllowed = isLockinPeriodAllowed; reccuringInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
this.lockinPeriod = lockinPeriod; } else if (savingProductType.isRegular()) {
this.lockinPeriodType = lockinPeriodType; futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure,
this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount(); savingInterestRate, commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod);
this.projectedInterestAccruedOnMaturity =futureValueOnMaturity.getAmount().subtract(BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue()*tenure.doubleValue())); }
}
this.product = product;
public void modifyAccount( this.externalId = externalId;
SavingProduct product, this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount();
String externalId, this.reccuringInterestRate = reccuringInterestRate;
Money savingsDeposit, this.savingInterestRate = savingInterestRate;
BigDecimal reccuringInterestRate, this.tenure = tenure;
BigDecimal savingInterestRate, this.projectedCommencementDate = commencementDate.toDate();
Integer tenure, this.tenureType = tenureTypeEnum;
LocalDate commencementDate, this.savingProductType = savingProductType;
TenureTypeEnum tenureTypeEnum, this.frequency = savingFrequencyType;
SavingProductType savingProductType, this.interestCalculationMethod = savingInterestCalculationMethod;
SavingFrequencyType savingFrequencyType, this.isLockinPeriodAllowed = isLockinPeriodAllowed;
SavingInterestCalculationMethod savingInterestCalculationMethod, this.lockinPeriod = lockinPeriod;
boolean isLockinPeriodAllowed, this.lockinPeriodType = lockinPeriodType;
Integer lockinPeriod,
PeriodFrequencyType lockinPeriodType, // FIXME - MADHUKAR - futureValueOnMaturity is possibly null
ReccuringDepositInterestCalculator reccuringDepositInterestCalculator) { this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.projectedInterestAccruedOnMaturity = futureValueOnMaturity.getAmount().subtract(
BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue() * tenure.doubleValue()));
Money futureValueOnMaturity = null; }
if(savingProductType.isReccuring()){
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, reccuringInterestRate, public boolean isDeleted() {
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod); return this.deleted;
} else if(savingProductType.isRegular()){ }
futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, savingInterestRate,
commencementDate, tenureTypeEnum, savingFrequencyType, savingInterestCalculationMethod); public boolean isPendingApproval() {
} return this.accountStatus.equals(100);
}
this.product = product;
this.externalId=externalId; public Client getClient() {
this.savingsDepositAmountPerPeriod=savingsDeposit.getAmount(); return client;
this.reccuringInterestRate=reccuringInterestRate; }
this.savingInterestRate = savingInterestRate;
this.tenure = tenure; public SavingProduct getProduct() {
this.projectedCommencementDate = commencementDate.toDate(); return product;
this.tenureType = tenureTypeEnum; }
this.savingProductType = savingProductType;
this.frequency =savingFrequencyType; public SavingProductType getSavingProductType() {
this.interestCalculationMethod = savingInterestCalculationMethod; return savingProductType;
this.isLockinPeriodAllowed = isLockinPeriodAllowed; }
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType; public String getExternalId() {
return externalId;
// FIXME - MADHUKAR - futureValueOnMaturity is possibly null }
this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount();
this.projectedInterestAccruedOnMaturity =futureValueOnMaturity.getAmount().subtract(BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue()*tenure.doubleValue())); public BigDecimal getSavingsDepositAmountPerPeriod() {
} return savingsDepositAmountPerPeriod;
}
public boolean isDeleted() {
return this.deleted; public BigDecimal getReccuringInterestRate() {
} return reccuringInterestRate;
}
public boolean isPendingApproval() {
return this.accountStatus.equals(100); public BigDecimal getSavingInterestRate() {
} return savingInterestRate;
}
public Client getClient() {
return client; public Integer getTenure() {
} return tenure;
}
public SavingProduct getProduct() {
return product; public TenureTypeEnum getTenureType() {
} return tenureType;
}
public SavingProductType getSavingProductType() {
return savingProductType; public SavingFrequencyType getFrequency() {
} return frequency;
}
public String getExternalId() {
return externalId; public SavingsInterestType getInterestType() {
} return interestType;
}
public BigDecimal getSavingsDepositAmountPerPeriod() {
return savingsDepositAmountPerPeriod; public SavingInterestCalculationMethod getInterestCalculationMethod() {
} return interestCalculationMethod;
}
public BigDecimal getReccuringInterestRate() {
return reccuringInterestRate; public Date getProjectedCommencementDate() {
} return projectedCommencementDate;
}
public BigDecimal getSavingInterestRate() {
return savingInterestRate; public BigDecimal getPreClosureInterestRate() {
} return preClosureInterestRate;
}
public Integer getTenure() {
return tenure; public boolean isPreClosureAllowed() {
} return preClosureAllowed;
}
public TenureTypeEnum getTenureType() {
return tenureType; public Date getWithdrawnOnDate() {
} return withdrawnOnDate;
}
public SavingFrequencyType getFrequency() {
return frequency; public boolean isLockinPeriodAllowed() {
} return isLockinPeriodAllowed;
}
public SavingsInterestType getInterestType() {
return interestType; public Integer getLockinPeriod() {
} return lockinPeriod;
}
public SavingInterestCalculationMethod getInterestCalculationMethod() {
return interestCalculationMethod; public PeriodFrequencyType getLockinPeriodType() {
} return lockinPeriodType;
}
public Date getProjectedCommencementDate() {
return projectedCommencementDate; public void addSavingScheduleInstallment(final SavingScheduleInstallments installment) {
} installment.updateAccount(this);
this.savingScheduleInstallments.add(installment);
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);
}
} }
@@ -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);
} }
} }
@@ -5,6 +5,5 @@ import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData;
public interface CalculateSavingSchedule { public interface CalculateSavingSchedule {
SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command); SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command);
} }
@@ -18,45 +18,43 @@ import org.springframework.stereotype.Service;
@Service @Service
public class CalculateSavingScheduleImpl implements CalculateSavingSchedule { public class CalculateSavingScheduleImpl implements CalculateSavingSchedule {
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final SavingProductRepository savingProductRepository; private final SavingProductRepository savingProductRepository;
private final SavingScheduleGenerator savingScheduleGenerator; private final SavingScheduleGenerator savingScheduleGenerator;
private final ApplicationCurrencyRepository applicationCurrencyRepository; private final ApplicationCurrencyRepository applicationCurrencyRepository;
@Autowired @Autowired
public CalculateSavingScheduleImpl( public CalculateSavingScheduleImpl(final PlatformSecurityContext context, final SavingProductRepository savingProductRepository,
final PlatformSecurityContext context, final ApplicationCurrencyRepository applicationCurrencyRepository) {
final SavingProductRepository savingProductRepository, this.context = context;
final ApplicationCurrencyRepository applicationCurrencyRepository) { this.savingProductRepository = savingProductRepository;
this.context = context; this.savingScheduleGenerator = new SavingScheduleGenerator();
this.savingProductRepository = savingProductRepository; this.applicationCurrencyRepository = applicationCurrencyRepository;
this.savingScheduleGenerator = new SavingScheduleGenerator(); }
this.applicationCurrencyRepository = applicationCurrencyRepository;
}
@Override @Override
public SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command) { public SavingScheduleData calculateSavingSchedule(CalculateSavingScheduleCommand command) {
context.authenticatedUser(); context.authenticatedUser();
// FIXME Validations should write here // FIXME Validations should write here
final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId()); final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId());
if (savingProduct == null) if (savingProduct == null) throw new SavingProductNotFoundException(command.getProductId());
throw new SavingProductNotFoundException(command.getProductId());
final Integer depositFrequency = command.getPayEvery(); final Integer depositFrequency = command.getPayEvery();
final PeriodFrequencyType depositFrequencyType = PeriodFrequencyType.fromInt(command.getPaymentFrequencyType()); final PeriodFrequencyType depositFrequencyType = PeriodFrequencyType.fromInt(command.getPaymentFrequencyType());
final LocalDate scheduleStartDate = command.getPaymentsStartingFromDate(); final LocalDate scheduleStartDate = command.getPaymentsStartingFromDate();
@SuppressWarnings("unused") @SuppressWarnings("unused")
final BigDecimal interestRate = command.getInterestRate(); final BigDecimal interestRate = command.getInterestRate();
final BigDecimal depositAmountPerPeriod = command.getDeposit(); final BigDecimal depositAmountPerPeriod = command.getDeposit();
final Integer tenure = command.getTenure(); final Integer tenure = command.getTenure();
final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneByCode(savingProduct.getCurrency().getCode()); final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneByCode(savingProduct.getCurrency()
.getCode());
SavingScheduleData savingScheduleData = savingScheduleGenerator.generate(scheduleStartDate,depositAmountPerPeriod, SavingScheduleData savingScheduleData = savingScheduleGenerator.generate(scheduleStartDate, depositAmountPerPeriod,
depositFrequency,depositFrequencyType,savingProduct,tenure,applicationCurrency); depositFrequency, depositFrequencyType, savingProduct, tenure, applicationCurrency);
return savingScheduleData; 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); List<LocalDate> duePaymentPeriodDates = new ArrayList<LocalDate>(depositFrequency);
LocalDate startDate = scheuleStartDate; LocalDate startDate = scheuleStartDate;
for (int period=1; period <= paymentPeriods; period++){ for (int period = 1; period <= paymentPeriods; period++) {
LocalDate duePaymentPeriodDate = startDate; LocalDate duePaymentPeriodDate = startDate;
if (period == 1) { if (period == 1) {
duePaymentPeriodDate = startDate; duePaymentPeriodDate = startDate;
} else { } else {
switch (depositFrequencyType) { switch (depositFrequencyType) {
case DAYS: case DAYS:
duePaymentPeriodDate = startDate.plusDays(depositFrequency); duePaymentPeriodDate = startDate.plusDays(depositFrequency);
break; break;
case WEEKS: case WEEKS:
duePaymentPeriodDate = startDate.plusWeeks(depositFrequency); duePaymentPeriodDate = startDate.plusWeeks(depositFrequency);
break; break;
case MONTHS: case MONTHS:
duePaymentPeriodDate = startDate.plusMonths(depositFrequency); duePaymentPeriodDate = startDate.plusMonths(depositFrequency);
break; break;
case YEARS: case YEARS:
duePaymentPeriodDate = startDate.plusYears(depositFrequency); duePaymentPeriodDate = startDate.plusYears(depositFrequency);
break; break;
case INVALID: case INVALID:
break; break;
} }
} }
duePaymentPeriodDates.add(duePaymentPeriodDate); duePaymentPeriodDates.add(duePaymentPeriodDate);
startDate = duePaymentPeriodDate; startDate = duePaymentPeriodDate;
} }
return duePaymentPeriodDates; return duePaymentPeriodDates;
} }
} }
@@ -34,190 +34,185 @@ import org.springframework.stereotype.Service;
@Service @Service
public class SavingAccountAssembler { public class SavingAccountAssembler {
private final ClientRepository clientRepository; private final ClientRepository clientRepository;
private final SavingProductRepository savingProductRepository; private final SavingProductRepository savingProductRepository;
private final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator; private final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator;
private final CalculateSavingSchedule calculateSavingSchedule; private final CalculateSavingSchedule calculateSavingSchedule;
@Autowired @Autowired
public SavingAccountAssembler(final ClientRepository clientRepository,final SavingProductRepository savingProductRepository, public SavingAccountAssembler(final ClientRepository clientRepository, final SavingProductRepository savingProductRepository,
final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator,final CalculateSavingSchedule calculateSavingSchedule) { final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator,
this.clientRepository=clientRepository; final CalculateSavingSchedule calculateSavingSchedule) {
this.savingProductRepository=savingProductRepository; this.clientRepository = clientRepository;
this.reccuringDepositInterestCalculator=reccuringDepositInterestCalculator; this.savingProductRepository = savingProductRepository;
this.calculateSavingSchedule = calculateSavingSchedule; this.reccuringDepositInterestCalculator = reccuringDepositInterestCalculator;
} this.calculateSavingSchedule = calculateSavingSchedule;
//minimumBalanceForWithdrawal,isPartialDepositAllowed }
public SavingAccount assembleFrom(SavingAccountCommand command){
Client client = this.clientRepository.findOne(command.getClientId()); // minimumBalanceForWithdrawal,isPartialDepositAllowed
if (client == null || client.isDeleted()) { public SavingAccount assembleFrom(SavingAccountCommand command) {
throw new ClientNotFoundException(command.getClientId());
}
SavingProduct product=this.savingProductRepository.findOne(command.getProductId()); Client client = this.clientRepository.findOne(command.getClientId());
if(product == null || product.isDeleted()){ if (client == null || client.isDeleted()) { throw new ClientNotFoundException(command.getClientId()); }
throw new SavingProductNotFoundException(command.getProductId());
}
MonetaryCurrency currency = product.getCurrency(); SavingProduct product = this.savingProductRepository.findOne(command.getProductId());
if(command.getCurrencyCode() != null && command.getDigitsAfterDecimal() != null){ if (product == null || product.isDeleted()) { throw new SavingProductNotFoundException(command.getProductId()); }
currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
}
Money savingsDeposit = Money.of(currency, command.getSavingsDepositAmount()); MonetaryCurrency currency = product.getCurrency();
if (command.getCurrencyCode() != null && command.getDigitsAfterDecimal() != null) {
currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
}
Integer tenure = product.getSavingProductRelatedDetail().getTenure(); Money savingsDeposit = Money.of(currency, command.getSavingsDepositAmount());
if(command.getTenure() != null){
tenure=command.getTenure();
}
TenureTypeEnum tenureTypeEnum=product.getSavingProductRelatedDetail().getTenureType(); Integer tenure = product.getSavingProductRelatedDetail().getTenure();
if (command.getTenureType() != null) { if (command.getTenure() != null) {
tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType()); tenure = command.getTenure();
} }
SavingProductType savingProductType= product.getSavingProductRelatedDetail().getSavingProductType(); TenureTypeEnum tenureTypeEnum = product.getSavingProductRelatedDetail().getTenureType();
if(command.getSavingProductType() != null){ if (command.getTenureType() != null) {
savingProductType = SavingProductType.fromInt(command.getSavingProductType()); tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType());
} }
SavingFrequencyType savingFrequencyType = product.getSavingProductRelatedDetail().getFrequency(); SavingProductType savingProductType = product.getSavingProductRelatedDetail().getSavingProductType();
if (command.getFrequency() != null) { if (command.getSavingProductType() != null) {
savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency()); savingProductType = SavingProductType.fromInt(command.getSavingProductType());
} }
SavingInterestCalculationMethod savingInterestCalculationMethod = product.getSavingProductRelatedDetail().getInterestCalculationMethod(); SavingFrequencyType savingFrequencyType = product.getSavingProductRelatedDetail().getFrequency();
if (command.getInterestCalculationMethod() != null) { if (command.getFrequency() != null) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod()); savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
} }
SavingsInterestType interestType = product.getSavingProductRelatedDetail().getInterestType(); SavingInterestCalculationMethod savingInterestCalculationMethod = product.getSavingProductRelatedDetail()
if (command.getInterestType() != null) { .getInterestCalculationMethod();
interestType = SavingsInterestType.fromInt(command.getInterestType()); if (command.getInterestCalculationMethod() != null) {
} savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
}
BigDecimal reccuringInterestRate = command.getRecurringInterestRate(); SavingsInterestType interestType = product.getSavingProductRelatedDetail().getInterestType();
BigDecimal savingInterestRate = product.getInterestRate(); if (command.getInterestType() != null) {
if(command.getSavingInterestRate() != null) interestType = SavingsInterestType.fromInt(command.getInterestType());
savingInterestRate = command.getSavingInterestRate(); }
boolean isLockinPeriodAllowed = product.getSavingProductRelatedDetail().isLockinPeriodAllowed(); BigDecimal reccuringInterestRate = command.getRecurringInterestRate();
if(command.isLockinPeriodChanged()){ BigDecimal savingInterestRate = product.getInterestRate();
isLockinPeriodAllowed = command.isLockinPeriodAllowed(); if (command.getSavingInterestRate() != null) savingInterestRate = command.getSavingInterestRate();
}
Integer lockinPeriod = product.getSavingProductRelatedDetail().getLockinPeriod(); boolean isLockinPeriodAllowed = product.getSavingProductRelatedDetail().isLockinPeriodAllowed();
if(command.getLockinPeriod() != null){ if (command.isLockinPeriodChanged()) {
lockinPeriod = command.getLockinPeriod(); isLockinPeriodAllowed = command.isLockinPeriodAllowed();
} }
PeriodFrequencyType lockinPeriodType = product.getSavingProductRelatedDetail().getLockinPeriodType(); Integer lockinPeriod = product.getSavingProductRelatedDetail().getLockinPeriod();
if(command.getLockinPeriodType() != null){ if (command.getLockinPeriod() != null) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); lockinPeriod = command.getLockinPeriod();
} }
SavingAccount account = SavingAccount.openNew(client, product, command.getExternalId(),savingsDeposit, PeriodFrequencyType lockinPeriodType = product.getSavingProductRelatedDetail().getLockinPeriodType();
reccuringInterestRate,savingInterestRate,tenure,command.getCommencementDate(),tenureTypeEnum, savingProductType, if (command.getLockinPeriodType() != null) {
savingFrequencyType, interestType, savingInterestCalculationMethod, isLockinPeriodAllowed,lockinPeriod, lockinPeriodType, lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
this.reccuringDepositInterestCalculator, defaultDepositLifecycleStateMachine()); }
SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command.toCalculateSavingScheduleCommand()); SavingAccount account = SavingAccount.openNew(client, product, command.getExternalId(), savingsDeposit, reccuringInterestRate,
for(SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()){ savingInterestRate, tenure, command.getCommencementDate(), tenureTypeEnum, savingProductType, savingFrequencyType,
interestType, savingInterestCalculationMethod, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType,
this.reccuringDepositInterestCalculator, defaultDepositLifecycleStateMachine());
final SavingScheduleInstallments installment = new SavingScheduleInstallments( SavingScheduleData savingScheduleData = this.calculateSavingSchedule.calculateSavingSchedule(command
account, .toCalculateSavingScheduleCommand());
savingSchedulePeriodData.getDueDate().toDate(), for (SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()) {
savingSchedulePeriodData.getPeriod(),
savingSchedulePeriodData.getDepositDue());
account.addSavingScheduleInstallment(installment);
}
return account; final SavingScheduleInstallments installment = new SavingScheduleInstallments(account, savingSchedulePeriodData.getDueDate()
} .toDate(), savingSchedulePeriodData.getPeriod(), savingSchedulePeriodData.getDepositDue());
account.addSavingScheduleInstallment(installment);
}
public void assembleFrom(SavingAccountCommand command, SavingAccount account) { return account;
}
SavingProduct product=account.getProduct(); public void assembleFrom(SavingAccountCommand command, SavingAccount account) {
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(); SavingProduct product = account.getProduct();
if(command.isExternalIdChanged()){ if (command.isProductIdChanged()) {
externalId = command.getExternalId(); if (product.getId() != command.getProductId()) {
} product = this.savingProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) throw new SavingProductNotFoundException(command.getProductId());
}
}
Money savingsDeposit = Money.of(product.getCurrency(), account.getSavingsDepositAmountPerPeriod()); String externalId = account.getExternalId();
if(command.isDepositAmountChanged()){ if (command.isExternalIdChanged()) {
savingsDeposit = Money.of(product.getCurrency(), command.getSavingsDepositAmount()); externalId = command.getExternalId();
} }
Integer tenure = account.getTenure();
if(command.isTenureInMonthsChanged()){
tenure = command.getTenure();
}
LocalDate commencementDate = new LocalDate(account.getProjectedCommencementDate()); Money savingsDeposit = Money.of(product.getCurrency(), account.getSavingsDepositAmountPerPeriod());
if (command.isCommencementDateChanged()) { if (command.isDepositAmountChanged()) {
commencementDate = command.getCommencementDate(); savingsDeposit = Money.of(product.getCurrency(), command.getSavingsDepositAmount());
} }
Integer tenure = account.getTenure();
if (command.isTenureInMonthsChanged()) {
tenure = command.getTenure();
}
TenureTypeEnum tenureTypeEnum=account.getTenureType(); LocalDate commencementDate = new LocalDate(account.getProjectedCommencementDate());
if(command.isTenureTypeEnumChanged()){ if (command.isCommencementDateChanged()) {
tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType()); commencementDate = command.getCommencementDate();
} }
SavingProductType savingProductType= account.getSavingProductType(); TenureTypeEnum tenureTypeEnum = account.getTenureType();
if (command.isSavingProductTypeChanged()) { if (command.isTenureTypeEnumChanged()) {
savingProductType = SavingProductType.fromInt(command.getSavingProductType()); tenureTypeEnum = TenureTypeEnum.fromInt(command.getTenureType());
} }
SavingFrequencyType savingFrequencyType = account.getFrequency(); SavingProductType savingProductType = account.getSavingProductType();
if (command.isSavingFrequencyTypeChanged()) { if (command.isSavingProductTypeChanged()) {
savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency()); savingProductType = SavingProductType.fromInt(command.getSavingProductType());
} }
SavingInterestCalculationMethod savingInterestCalculationMethod =account.getInterestCalculationMethod(); SavingFrequencyType savingFrequencyType = account.getFrequency();
if (command.isSavingInterestCalculationMethodChanged()) { if (command.isSavingFrequencyTypeChanged()) {
savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod()); savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
} }
BigDecimal reccuringInterestRate = account.getReccuringInterestRate(); SavingInterestCalculationMethod savingInterestCalculationMethod = account.getInterestCalculationMethod();
if (command.isReccuringInterestRateChanged()) { if (command.isSavingInterestCalculationMethodChanged()) {
reccuringInterestRate = command.getRecurringInterestRate(); savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
} }
BigDecimal savingInterestRate = account.getSavingInterestRate(); BigDecimal reccuringInterestRate = account.getReccuringInterestRate();
if (command.isSavingInterestRateChanged()) { if (command.isReccuringInterestRateChanged()) {
savingInterestRate = command.getSavingInterestRate(); reccuringInterestRate = command.getRecurringInterestRate();
} }
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); BigDecimal savingInterestRate = account.getSavingInterestRate();
if (command.isLockinPeriodAllowedChanged()) { if (command.isSavingInterestRateChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed(); savingInterestRate = command.getSavingInterestRate();
} }
Integer lockinPeriod =account.getLockinPeriod(); boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
if (command.isLockinPeriodChanged()) { if (command.isLockinPeriodAllowedChanged()) {
lockinPeriod = command.getLockinPeriod(); isLockinPeriodAllowed = command.isLockinPeriodAllowed();
} }
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType(); Integer lockinPeriod = account.getLockinPeriod();
if (command.isLockinPeriodTypeChanged()) { if (command.isLockinPeriodChanged()) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); lockinPeriod = command.getLockinPeriod();
} }
account.modifyAccount(product, externalId, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure,
commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, savingInterestCalculationMethod,
isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, this.reccuringDepositInterestCalculator);
} 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); private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() {
} List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values());
return new DepositLifecycleStateMachineImpl(allowedDepositStatuses);
}
} }
@@ -15,30 +15,26 @@ import org.springframework.stereotype.Service;
@Service @Service
public class SavingProductRelatedDetailAssembler { public class SavingProductRelatedDetailAssembler {
private final SavingProductRepository savingProductRepository; private final SavingProductRepository savingProductRepository;
@Autowired @Autowired
public SavingProductRelatedDetailAssembler(final SavingProductRepository savingProductRepository) { public SavingProductRelatedDetailAssembler(final SavingProductRepository savingProductRepository) {
this.savingProductRepository = savingProductRepository; this.savingProductRepository = savingProductRepository;
} }
public SavingProductRelatedDetail assembleFrom(CalculateSavingScheduleCommand command) { public SavingProductRelatedDetail assembleFrom(CalculateSavingScheduleCommand command) {
final BigDecimal depositAmountForPeriod = command.getDeposit(); final BigDecimal depositAmountForPeriod = command.getDeposit();
final BigDecimal depositInterestRate = command.getInterestRate(); final BigDecimal depositInterestRate = command.getInterestRate();
final LocalDate installmentDate = command.getPaymentsStartingFromDate(); final LocalDate installmentDate = command.getPaymentsStartingFromDate();
final Integer payEvery = command.getPayEvery(); final Integer payEvery = command.getPayEvery();
final Integer paymentFrequencyType = command.getPaymentFrequencyType(); final Integer paymentFrequencyType = command.getPaymentFrequencyType();
final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId()); final SavingProduct savingProduct = this.savingProductRepository.findOne(command.getProductId());
if (savingProduct == null) { if (savingProduct == null) { throw new SavingProductNotFoundException(command.getProductId()); }
throw new SavingProductNotFoundException(command.getProductId());
}
final MonetaryCurrency currency = savingProduct.getCurrency();
return null;
}
final MonetaryCurrency currency = savingProduct.getCurrency();
return null;
}
} }
@@ -18,41 +18,34 @@ import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct;
public class SavingScheduleGenerator { public class SavingScheduleGenerator {
private final DepositScheduleDateGenerator scheduledDateGenerator = new DefaultDepositScheduleDateGenerator(); private final DepositScheduleDateGenerator scheduledDateGenerator = new DefaultDepositScheduleDateGenerator();
public SavingScheduleData generate( public SavingScheduleData generate(final LocalDate scheduleStartDate, final BigDecimal depositAmountPerPeriod,
final LocalDate scheduleStartDate, final Integer depositFrequency, final PeriodFrequencyType depositFrequencyType, final SavingProduct savingProduct,
final BigDecimal depositAmountPerPeriod, final Integer tenure, final ApplicationCurrency applicationCurrency) {
final Integer depositFrequency,
final PeriodFrequencyType depositFrequencyType,
final SavingProduct savingProduct,
final Integer tenure,
final ApplicationCurrency applicationCurrency) {
LocalDate startDate = scheduleStartDate; LocalDate startDate = scheduleStartDate;
int periodNumber = 1; int periodNumber = 1;
Integer paymentPeriods = tenure/depositFrequency; Integer paymentPeriods = tenure / depositFrequency;
final Collection<SavingSchedulePeriodData> periods = new ArrayList<SavingSchedulePeriodData>(); final Collection<SavingSchedulePeriodData> periods = new ArrayList<SavingSchedulePeriodData>();
final List<LocalDate> scheduledDates = this.scheduledDateGenerator.generate(startDate,paymentPeriods,depositFrequency,depositFrequencyType); final List<LocalDate> scheduledDates = this.scheduledDateGenerator.generate(startDate, paymentPeriods, depositFrequency,
final MonetaryCurrency currency = savingProduct.getCurrency(); 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){ for (LocalDate scheduleDate : scheduledDates) {
totalDeposit = totalDeposit.plus(depositAmount); totalDeposit = totalDeposit.plus(depositAmount);
SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(periodNumber, scheduleDate, depositAmount.getAmount()); SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(periodNumber, scheduleDate,
periods.add(installment); depositAmount.getAmount());
periodNumber++; periods.add(installment);
} periodNumber++;
CurrencyData currencyData = new CurrencyData( }
applicationCurrency.getCode(), CurrencyData currencyData = new CurrencyData(applicationCurrency.getCode(), applicationCurrency.getName(),
applicationCurrency.getName(), currency.getDigitsAfterDecimal(), applicationCurrency.getDisplaySymbol(), applicationCurrency.getNameCode());
currency.getDigitsAfterDecimal(),
applicationCurrency.getDisplaySymbol(),
applicationCurrency.getNameCode());
return new SavingScheduleData(currencyData, totalDeposit.getAmount(), periods); return new SavingScheduleData(currencyData, totalDeposit.getAmount(), periods);
} }
} }
@@ -47,164 +47,167 @@ import org.springframework.stereotype.Component;
@Scope("singleton") @Scope("singleton")
public class SavingProductsApiResource { public class SavingProductsApiResource {
@Autowired @Autowired
private SavingProductReadPlatformService savingProductReadPlatformService; private SavingProductReadPlatformService savingProductReadPlatformService;
@Autowired @Autowired
private SavingProductWritePlatformService savingProductWritePlatformService; private SavingProductWritePlatformService savingProductWritePlatformService;
@Autowired @Autowired
private PortfolioApiDataConversionService apiDataConversionService; 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 @POST
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public Response createSavingProduct(final String jsonRequestBody){ public Response createSavingProduct(final String jsonRequestBody) {
final SavingProductCommand command=this.apiDataConversionService.convertJsonToSavingProductCommand(null, jsonRequestBody); final SavingProductCommand command = this.apiDataConversionService.convertJsonToSavingProductCommand(null, jsonRequestBody);
EntityIdentifier entityIdentifier=this.savingProductWritePlatformService.createSavingProduct(command); EntityIdentifier entityIdentifier = this.savingProductWritePlatformService.createSavingProduct(command);
return Response.ok().entity(entityIdentifier).build(); return Response.ok().entity(entityIdentifier).build();
} }
@PUT @PUT
@Path("{productId}") @Path("{productId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public Response updateSavingProduct(@PathParam("productId") final Long productId, final String jsonRequestBody){ public Response updateSavingProduct(@PathParam("productId") final Long productId, final String jsonRequestBody) {
SavingProductCommand command=this.apiDataConversionService.convertJsonToSavingProductCommand(productId, jsonRequestBody); SavingProductCommand command = this.apiDataConversionService.convertJsonToSavingProductCommand(productId, jsonRequestBody);
EntityIdentifier entityIdentifier=this.savingProductWritePlatformService.updateSavingProduct(command); EntityIdentifier entityIdentifier = this.savingProductWritePlatformService.updateSavingProduct(command);
return Response.ok().entity(entityIdentifier).build(); return Response.ok().entity(entityIdentifier).build();
} }
@GET @GET
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveAllSavingProducts(@Context final UriInfo uriInfo) { public String retrieveAllSavingProducts(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", "locale", "name",
"locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate", "minInterestRate","maxInterestRate", "description", "currencyCode", "digitsAfterDecimal", "interstRate", "minInterestRate", "maxInterestRate",
"savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod", "savingsDepositAmount", "savingProductType", "tenureType", "tenure", "frequency", "interestType",
"minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType")); "interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "isLockinPeriodAllowed",
"lockinPeriod", "lockinPeriodType"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters); responseParameters.addAll(typicalResponseParameters);
} }
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<SavingProductData> products = this.savingProductReadPlatformService.retrieveAllSavingProducts(); Collection<SavingProductData> products = this.savingProductReadPlatformService.retrieveAllSavingProducts();
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, products); return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, products);
} }
@GET @GET
@Path("{productId}") @Path("{productId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveSavingProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) { public String retrieveSavingProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", "locale", "name",
"locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate", "minInterestRate","maxInterestRate", "description", "currencyCode", "digitsAfterDecimal", "interstRate", "minInterestRate", "maxInterestRate",
"savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod", "savingsDepositAmount", "savingProductType", "tenureType", "tenure", "frequency", "interestType",
"minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType")); "interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "isLockinPeriodAllowed",
"lockinPeriod", "lockinPeriodType"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters); responseParameters.addAll(typicalResponseParameters);
} }
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
if (template) { if (template) {
responseParameters.addAll(Arrays.asList("currencyOptions")); responseParameters.addAll(Arrays.asList("currencyOptions"));
} }
SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveSavingProduct(productId); SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveSavingProduct(productId);
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct); return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct);
} }
@GET @GET
@Path("template") @Path("template")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveNewSavingProductDetails(@Context final UriInfo uriInfo) { public String retrieveNewSavingProductDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> typicalResponseParameters = new HashSet<String>( Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "createdOn", "lastModifedOn", "locale", "name",
Arrays.asList("id", "createdOn", "lastModifedOn", "description", "currencyCode", "digitsAfterDecimal", "interstRate", "savingsDepositAmount", "savingProductType",
"locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate", "tenureType", "tenure", "frequency", "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal",
"savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod", "isPartialDepositAllowed", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "currencyOptions"));
"minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType","currencyOptions"));
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters); responseParameters.addAll(typicalResponseParameters);
} }
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveNewSavingProductDetails(); SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveNewSavingProductDetails();
savingProduct = handleTemplateRelatedData(responseParameters,savingProduct); savingProduct = handleTemplateRelatedData(responseParameters, savingProduct);
return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct); return this.apiJsonSerializerService.serializeSavingProductDataToJson(prettyPrint, responseParameters, savingProduct);
} }
private SavingProductData handleTemplateRelatedData(Set<String> responseParameters, SavingProductData savingProduct) { private SavingProductData handleTemplateRelatedData(Set<String> responseParameters, SavingProductData savingProduct) {
responseParameters.addAll(Arrays.asList("currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions", "savingFrequencyOptions", "savingsInterestTypeOptions", responseParameters.addAll(Arrays.asList("currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions",
"lockinPeriodTypeOptions", "interestCalculationOptions")); "savingFrequencyOptions", "savingsInterestTypeOptions", "lockinPeriodTypeOptions", "interestCalculationOptions"));
List<CurrencyData> currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); List<CurrencyData> currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies();
EnumOptionData reccuring = SavingProductEnumerations.savingProductType(SavingProductType.RECCURING); EnumOptionData reccuring = SavingProductEnumerations.savingProductType(SavingProductType.RECCURING);
EnumOptionData regular = SavingProductEnumerations.savingProductType(SavingProductType.REGULAR); EnumOptionData regular = SavingProductEnumerations.savingProductType(SavingProductType.REGULAR);
List<EnumOptionData> savingsProductTypeOptions = Arrays.asList(reccuring,regular); List<EnumOptionData> savingsProductTypeOptions = Arrays.asList(reccuring, regular);
EnumOptionData fixed = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD); EnumOptionData fixed = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD);
EnumOptionData perpetual = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.PERPETUAL); EnumOptionData perpetual = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.PERPETUAL);
List<EnumOptionData> tenureTypeOptions = Arrays.asList(fixed,perpetual); List<EnumOptionData> tenureTypeOptions = Arrays.asList(fixed, perpetual);
EnumOptionData monthly = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY); EnumOptionData monthly = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY);
List<EnumOptionData> savingFrequencyOptions = Arrays.asList(monthly); List<EnumOptionData> savingFrequencyOptions = Arrays.asList(monthly);
EnumOptionData simple = SavingProductEnumerations.savingInterestType(SavingsInterestType.SIMPLE); EnumOptionData simple = SavingProductEnumerations.savingInterestType(SavingsInterestType.SIMPLE);
EnumOptionData compounding = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING); EnumOptionData compounding = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING);
List<EnumOptionData> savingsInterestTypeOptions = Arrays.asList(simple,compounding); List<EnumOptionData> savingsInterestTypeOptions = Arrays.asList(simple, compounding);
EnumOptionData months = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS); EnumOptionData months = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS);
List<EnumOptionData> lockinPeriodTypeOptions = Arrays.asList(months); List<EnumOptionData> lockinPeriodTypeOptions = Arrays.asList(months);
EnumOptionData averagebal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL); EnumOptionData averagebal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL);
EnumOptionData minbal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MINBAL); EnumOptionData minbal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MINBAL);
EnumOptionData monthlyCollection = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MONTHLYCOLLECTION); EnumOptionData monthlyCollection = SavingProductEnumerations
List<EnumOptionData> interestCalculationOptions= Arrays.asList(averagebal,minbal,monthlyCollection); .savingInterestCalculationMethod(SavingInterestCalculationMethod.MONTHLYCOLLECTION);
List<EnumOptionData> interestCalculationOptions = Arrays.asList(averagebal, minbal, monthlyCollection);
return new SavingProductData(savingProduct,currencyOptions,savingsProductTypeOptions,tenureTypeOptions,savingFrequencyOptions,savingsInterestTypeOptions,lockinPeriodTypeOptions,interestCalculationOptions); return new SavingProductData(savingProduct, currencyOptions, savingsProductTypeOptions, tenureTypeOptions, savingFrequencyOptions,
} savingsInterestTypeOptions, lockinPeriodTypeOptions, interestCalculationOptions);
}
@DELETE @DELETE
@Path("{productId}") @Path("{productId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public Response deleteProduct(@PathParam("productId") final Long productId) { public Response deleteProduct(@PathParam("productId") final Long productId) {
this.savingProductWritePlatformService.deleteSavingProduct(productId); this.savingProductWritePlatformService.deleteSavingProduct(productId);
return Response.ok(new EntityIdentifier(productId)).build(); 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 String currencyCode;
private final Integer savingProductType; private final Integer digitsAfterDecimal;
private final Integer tenureType; private final BigDecimal interestRate;
private final Integer tenure; private final BigDecimal minInterestRate;
private final Integer frequency; private final BigDecimal maxInterestRate;
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 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 Set<String> modifiedParameters;
public SavingProductCommand(Set<String> modifiedParameters, public SavingProductCommand(Set<String> modifiedParameters, Long id, String name, String description, String currencyCode,
Long id, String name, String description, Integer digitsAfterDecimal, BigDecimal interestRate, BigDecimal minInterestRate, BigDecimal maxInterestRate,
String currencyCode, Integer digitsAfterDecimal, BigDecimal savingsDepositAmount, Integer savingProductType, Integer tenureType, Integer tenure, Integer frequency,
BigDecimal interestRate, BigDecimal minInterestRate, Integer interestType, Integer interestCalculationMethod, BigDecimal minimumBalanceForWithdrawal,
BigDecimal maxInterestRate, BigDecimal savingsDepositAmount, boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, Integer lockinPeriod, Integer lockinPeriodType) {
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.id = id;
this.name = name; this.name = name;
this.description = description; this.description = description;
this.currencyCode = currencyCode; this.currencyCode = currencyCode;
this.digitsAfterDecimal = digitsAfterDecimal; this.digitsAfterDecimal = digitsAfterDecimal;
this.interestRate = interestRate; this.interestRate = interestRate;
this.minInterestRate = minInterestRate; this.minInterestRate = minInterestRate;
this.maxInterestRate = maxInterestRate; this.maxInterestRate = maxInterestRate;
this.savingsDepositAmount=savingsDepositAmount; this.savingsDepositAmount = savingsDepositAmount;
this.savingProductType=savingProductType; this.savingProductType = savingProductType;
this.tenureType=tenureType; this.tenureType = tenureType;
this.tenure=tenure; this.tenure = tenure;
this.frequency=frequency; this.frequency = frequency;
this.interestType=interestType; this.interestType = interestType;
this.interestCalculationMethod=interestCalculationMethod; this.interestCalculationMethod = interestCalculationMethod;
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal; this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.isPartialDepositAllowed=isPartialDepositAllowed; this.isPartialDepositAllowed = isPartialDepositAllowed;
this.isLockinPeriodAllowed=isLockinPeriodAllowed; this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod=lockinPeriod; this.lockinPeriod = lockinPeriod;
this.lockinPeriodType=lockinPeriodType; this.lockinPeriodType = lockinPeriodType;
this.modifiedParameters = modifiedParameters; this.modifiedParameters = modifiedParameters;
} }
public Long getId() { public Long getId() {
return id; return id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public String getCurrencyCode() { public String getCurrencyCode() {
return currencyCode; return currencyCode;
} }
public Integer getDigitsAfterDecimal() { public Integer getDigitsAfterDecimal() {
return digitsAfterDecimal; return digitsAfterDecimal;
} }
public BigDecimal getInterestRate() { public BigDecimal getInterestRate() {
return interestRate; return interestRate;
} }
public BigDecimal getMinInterestRate() { public BigDecimal getMinInterestRate() {
return minInterestRate; return minInterestRate;
} }
public BigDecimal getMaxInterestRate() { public BigDecimal getMaxInterestRate() {
return maxInterestRate; return maxInterestRate;
} }
public BigDecimal getSavingsDepositAmount() { public BigDecimal getSavingsDepositAmount() {
return savingsDepositAmount; return savingsDepositAmount;
} }
public Integer getSavingProductType() { public Integer getSavingProductType() {
return savingProductType; return savingProductType;
} }
public Integer getTenureType() { public Integer getTenureType() {
return tenureType; return tenureType;
} }
public Integer getTenure() { public Integer getTenure() {
return tenure; return tenure;
} }
public Integer getFrequency() { public Integer getFrequency() {
return frequency; return frequency;
} }
public Integer getInterestType() { public Integer getInterestType() {
return interestType; return interestType;
} }
public Integer getInterestCalculationMethod() { public Integer getInterestCalculationMethod() {
return interestCalculationMethod; return interestCalculationMethod;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public BigDecimal getMinimumBalanceForWithdrawal() {
return minimumBalanceForWithdrawal; return minimumBalanceForWithdrawal;
} }
public boolean isPartialDepositAllowed() { public boolean isPartialDepositAllowed() {
return isPartialDepositAllowed; return isPartialDepositAllowed;
} }
public boolean isLockinPeriodAllowed() { public boolean isLockinPeriodAllowed() {
return isLockinPeriodAllowed; return isLockinPeriodAllowed;
} }
public Integer getLockinPeriod() { public Integer getLockinPeriod() {
return lockinPeriod; return lockinPeriod;
} }
public Integer getLockinPeriodType() { public Integer getLockinPeriodType() {
return lockinPeriodType; return lockinPeriodType;
} }
public boolean isNameChanged() { public boolean isNameChanged() {
return this.modifiedParameters.contains("name"); return this.modifiedParameters.contains("name");
} }
public boolean isDescriptionChanged() { public boolean isDescriptionChanged() {
return this.modifiedParameters.contains("description"); return this.modifiedParameters.contains("description");
} }
public boolean isCurrencyCodeChanged() { public boolean isCurrencyCodeChanged() {
return this.modifiedParameters.contains("currencyCode"); return this.modifiedParameters.contains("currencyCode");
} }
public boolean isDigitsAfterDecimalChanged() { public boolean isDigitsAfterDecimalChanged() {
return this.modifiedParameters.contains("digitsAfterDecimal"); return this.modifiedParameters.contains("digitsAfterDecimal");
} }
public boolean isInterestRateChanged() { public boolean isInterestRateChanged() {
return this.modifiedParameters.contains("interestRate"); return this.modifiedParameters.contains("interestRate");
} }
public boolean isSavingsDepositAmountChanged(){ public boolean isSavingsDepositAmountChanged() {
return this.modifiedParameters.contains("savingsDepositAmount"); return this.modifiedParameters.contains("savingsDepositAmount");
} }
public boolean isSavingProductTypeChanged() { public boolean isSavingProductTypeChanged() {
return this.modifiedParameters.contains("savingProductType"); return this.modifiedParameters.contains("savingProductType");
} }
public boolean isTenureTypeChanged() { public boolean isTenureTypeChanged() {
return this.modifiedParameters.contains("tenureType"); return this.modifiedParameters.contains("tenureType");
} }
public boolean isTenureChanged() { public boolean isTenureChanged() {
return this.modifiedParameters.contains("tenure"); return this.modifiedParameters.contains("tenure");
} }
public boolean isFrequencyChanged() { public boolean isFrequencyChanged() {
return this.modifiedParameters.contains("frequency"); return this.modifiedParameters.contains("frequency");
} }
public boolean isInterestTypeChanged() { public boolean isInterestTypeChanged() {
return this.modifiedParameters.contains("interestType"); return this.modifiedParameters.contains("interestType");
} }
public boolean isInterestCalculationMethodChanged() { public boolean isInterestCalculationMethodChanged() {
return this.modifiedParameters.contains("interestCalculationMethod"); return this.modifiedParameters.contains("interestCalculationMethod");
} }
public boolean isMinimumBalanceForWithdrawalChanged() { public boolean isMinimumBalanceForWithdrawalChanged() {
return this.modifiedParameters.contains("minimumBalanceForWithdrawal"); return this.modifiedParameters.contains("minimumBalanceForWithdrawal");
} }
public boolean isPartialDepositAllowedChanged() { public boolean isPartialDepositAllowedChanged() {
return this.modifiedParameters.contains("isPartialDepositAllowed"); return this.modifiedParameters.contains("isPartialDepositAllowed");
} }
public boolean isLockinPeriodAllowedChanged() { public boolean isLockinPeriodAllowedChanged() {
return this.modifiedParameters.contains("isLockinPeriodAllowed"); return this.modifiedParameters.contains("isLockinPeriodAllowed");
} }
public boolean isLockinPeriodChanged() { public boolean isLockinPeriodChanged() {
return this.modifiedParameters.contains("lockinPeriod"); return this.modifiedParameters.contains("lockinPeriod");
} }
public boolean isLockinPeriodTypeChanged() { public boolean isLockinPeriodTypeChanged() {
return this.modifiedParameters.contains("lockinPeriodType"); 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 interestRate;
private final BigDecimal minInterestRate; private final BigDecimal minInterestRate;
private final BigDecimal maxInterestRate; private final BigDecimal maxInterestRate;
private final BigDecimal savingsDepositAmount; private final BigDecimal savingsDepositAmount;
private final EnumOptionData savingProductType; private final EnumOptionData savingProductType;
private final EnumOptionData tenureType; private final EnumOptionData tenureType;
private final Integer tenure; private final Integer tenure;
private final EnumOptionData savingFrequencyType; private final EnumOptionData savingFrequencyType;
private final EnumOptionData interestType; private final EnumOptionData interestType;
private final EnumOptionData interestCalculationMethod; private final EnumOptionData interestCalculationMethod;
private final BigDecimal minimumBalanceForWithdrawal; private final BigDecimal minimumBalanceForWithdrawal;
private final boolean isPartialDepositAllowed; private final boolean isPartialDepositAllowed;
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 DateTime createdOn; private DateTime createdOn;
private DateTime lastModifedOn; private DateTime lastModifedOn;
private List<CurrencyData> currencyOptions = new ArrayList<CurrencyData>(); private List<CurrencyData> currencyOptions = new ArrayList<CurrencyData>();
List<EnumOptionData> savingsProductTypeOptions = new ArrayList<EnumOptionData>(); List<EnumOptionData> savingsProductTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> tenureTypeOptions = new ArrayList<EnumOptionData>(); List<EnumOptionData> tenureTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> savingFrequencyOptions = new ArrayList<EnumOptionData>(); List<EnumOptionData> savingFrequencyOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> savingsInterestTypeOptions = new ArrayList<EnumOptionData>(); List<EnumOptionData> savingsInterestTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> lockinPeriodTypeOptions = new ArrayList<EnumOptionData>(); List<EnumOptionData> lockinPeriodTypeOptions = new ArrayList<EnumOptionData>();
List<EnumOptionData> interestCalculationOptions = new ArrayList<EnumOptionData>(); List<EnumOptionData> interestCalculationOptions = new ArrayList<EnumOptionData>();
public SavingProductData(){ public SavingProductData() {
this.createdOn=new DateTime(); this.createdOn = new DateTime();
this.lastModifedOn=new DateTime(); this.lastModifedOn = new DateTime();
this.id=null; this.id = null;
this.name=null; this.name = null;
this.description=null; this.description = null;
this.interestRate=BigDecimal.ZERO; this.interestRate = BigDecimal.ZERO;
this.minInterestRate=BigDecimal.ZERO; this.minInterestRate = BigDecimal.ZERO;
this.maxInterestRate=BigDecimal.ZERO; this.maxInterestRate = BigDecimal.ZERO;
this.currency=null; this.currency = null;
this.digitsAfterDecimal=null; this.digitsAfterDecimal = null;
this.savingsDepositAmount=null; this.savingsDepositAmount = null;
this.savingProductType=null; this.savingProductType = null;
this.tenureType = null; this.tenureType = null;
this.tenure = null; this.tenure = null;
this.savingFrequencyType=null; this.savingFrequencyType = null;
this.interestType=null; this.interestType = null;
this.interestCalculationMethod=null; this.interestCalculationMethod = null;
this.minimumBalanceForWithdrawal=null; this.minimumBalanceForWithdrawal = null;
this.isPartialDepositAllowed=true; this.isPartialDepositAllowed = true;
this.isLockinPeriodAllowed=true; this.isLockinPeriodAllowed = true;
this.lockinPeriod=null; this.lockinPeriod = null;
this.lockinPeriodType=null; this.lockinPeriodType = null;
} }
public SavingProductData(DateTime createdOn, DateTime lastModifedOn, public SavingProductData(DateTime createdOn, DateTime lastModifedOn, Long id, String name, String description, BigDecimal interestRate,
Long id, String name, String description, BigDecimal minInterestRate, BigDecimal maxInterestRate, CurrencyData currency, Integer digitsAfterDecimal,
BigDecimal interestRate, BigDecimal minInterestRate, BigDecimal maxInterestRate, CurrencyData currency, BigDecimal savingsDepositAmount, EnumOptionData savingProductType, EnumOptionData tenureType, Integer tenure,
Integer digitsAfterDecimal, BigDecimal savingsDepositAmount, EnumOptionData savingFrequencyType, EnumOptionData savingInterestType, EnumOptionData interestCalculationMethod,
EnumOptionData savingProductType, BigDecimal minimumBalanceForWithdrawal, boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, Integer lockinPeriod,
EnumOptionData tenureType, Integer tenure, EnumOptionData lockinPeriodType) {
EnumOptionData savingFrequencyType, this.createdOn = createdOn;
EnumOptionData savingInterestType, this.lastModifedOn = lastModifedOn;
EnumOptionData interestCalculationMethod, this.id = id;
BigDecimal minimumBalanceForWithdrawal, this.name = name;
boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, this.description = description;
Integer lockinPeriod, EnumOptionData lockinPeriodType) { this.interestRate = interestRate;
this.createdOn=createdOn; this.minInterestRate = minInterestRate;
this.lastModifedOn=lastModifedOn; this.maxInterestRate = maxInterestRate;
this.id=id; this.currency = currency;
this.name=name; this.digitsAfterDecimal = digitsAfterDecimal;
this.description=description; this.savingsDepositAmount = savingsDepositAmount;
this.interestRate=interestRate; this.savingProductType = savingProductType;
this.minInterestRate=minInterestRate; this.tenureType = tenureType;
this.maxInterestRate=maxInterestRate; this.tenure = tenure;
this.currency=currency; this.savingFrequencyType = savingFrequencyType;
this.digitsAfterDecimal=digitsAfterDecimal; this.interestType = savingInterestType;
this.savingsDepositAmount=savingsDepositAmount; this.interestCalculationMethod = interestCalculationMethod;
this.savingProductType=savingProductType; this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.tenureType = tenureType; this.isPartialDepositAllowed = isPartialDepositAllowed;
this.tenure = tenure; this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.savingFrequencyType=savingFrequencyType; this.lockinPeriod = lockinPeriod;
this.interestType=savingInterestType; this.lockinPeriodType = lockinPeriodType;
this.interestCalculationMethod=interestCalculationMethod; }
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal;
this.isPartialDepositAllowed=isPartialDepositAllowed;
this.isLockinPeriodAllowed=isLockinPeriodAllowed;
this.lockinPeriod=lockinPeriod;
this.lockinPeriodType=lockinPeriodType;
}
public SavingProductData(SavingProductData product, public SavingProductData(SavingProductData product, List<CurrencyData> currencyOptions, List<EnumOptionData> savingsProductTypeOptions,
List<CurrencyData> currencyOptions, List<EnumOptionData> tenureTypeOptions, List<EnumOptionData> savingFrequencyOptions,
List<EnumOptionData> savingsProductTypeOptions, List<EnumOptionData> savingsInterestTypeOptions, List<EnumOptionData> lockinPeriodTypeOptions,
List<EnumOptionData> tenureTypeOptions, List<EnumOptionData> interestCalculationOptions) {
List<EnumOptionData> savingFrequencyOptions,
List<EnumOptionData> savingsInterestTypeOptions,
List<EnumOptionData> lockinPeriodTypeOptions,
List<EnumOptionData> interestCalculationOptions) {
this.createdOn=product.getCreatedOn(); this.createdOn = product.getCreatedOn();
this.lastModifedOn=product.getLastModifedOn(); this.lastModifedOn = product.getLastModifedOn();
this.id=product.getId(); this.id = product.getId();
this.name=product.getName(); this.name = product.getName();
this.description=product.getDescription(); this.description = product.getDescription();
this.interestRate=product.getInterestRate(); this.interestRate = product.getInterestRate();
this.minInterestRate=product.getMinInterestRate(); this.minInterestRate = product.getMinInterestRate();
this.maxInterestRate=product.getMaxInterestRate(); this.maxInterestRate = product.getMaxInterestRate();
this.currency=product.getCurrency(); this.currency = product.getCurrency();
this.digitsAfterDecimal=product.getDigitsAfterDecimal(); this.digitsAfterDecimal = product.getDigitsAfterDecimal();
this.savingsDepositAmount=product.getSavingsDepositAmount(); this.savingsDepositAmount = product.getSavingsDepositAmount();
this.savingProductType=product.getSavingProductType(); this.savingProductType = product.getSavingProductType();
this.tenureType = product.getTenureType(); this.tenureType = product.getTenureType();
this.tenure = product.getTenure(); this.tenure = product.getTenure();
this.savingFrequencyType=product.getSavingFrequencyType(); this.savingFrequencyType = product.getSavingFrequencyType();
this.interestType=product.getInterestType(); this.interestType = product.getInterestType();
this.interestCalculationMethod=product.getInterestCalculationMethod(); this.interestCalculationMethod = product.getInterestCalculationMethod();
this.minimumBalanceForWithdrawal=product.getMinimumBalanceForWithdrawal(); this.minimumBalanceForWithdrawal = product.getMinimumBalanceForWithdrawal();
this.isPartialDepositAllowed=product.isPartialDepositAllowed(); this.isPartialDepositAllowed = product.isPartialDepositAllowed();
this.isLockinPeriodAllowed=product.isLockinPeriodAllowed(); this.isLockinPeriodAllowed = product.isLockinPeriodAllowed();
this.lockinPeriod=product.getLockinPeriod(); this.lockinPeriod = product.getLockinPeriod();
this.lockinPeriodType=product.getLockinPeriodType(); this.lockinPeriodType = product.getLockinPeriodType();
this.currencyOptions=currencyOptions; this.currencyOptions = currencyOptions;
this.savingsProductTypeOptions=savingsProductTypeOptions; this.savingsProductTypeOptions = savingsProductTypeOptions;
this.tenureTypeOptions=tenureTypeOptions; this.tenureTypeOptions = tenureTypeOptions;
this.savingFrequencyOptions=savingFrequencyOptions; this.savingFrequencyOptions = savingFrequencyOptions;
this.savingsInterestTypeOptions=savingsInterestTypeOptions; this.savingsInterestTypeOptions = savingsInterestTypeOptions;
this.lockinPeriodTypeOptions=lockinPeriodTypeOptions; this.lockinPeriodTypeOptions = lockinPeriodTypeOptions;
this.interestCalculationOptions=interestCalculationOptions; this.interestCalculationOptions = interestCalculationOptions;
} }
public Long getId() { public Long getId() {
return id; return id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public CurrencyData getCurrency() { public CurrencyData getCurrency() {
return currency; return currency;
} }
public Integer getDigitsAfterDecimal() { public Integer getDigitsAfterDecimal() {
return digitsAfterDecimal; return digitsAfterDecimal;
} }
public BigDecimal getInterestRate() { public BigDecimal getInterestRate() {
return interestRate; return interestRate;
} }
public BigDecimal getMinInterestRate() { public BigDecimal getMinInterestRate() {
return minInterestRate; return minInterestRate;
} }
public BigDecimal getMaxInterestRate() { public BigDecimal getMaxInterestRate() {
return maxInterestRate; return maxInterestRate;
} }
public BigDecimal getSavingsDepositAmount() { public BigDecimal getSavingsDepositAmount() {
return savingsDepositAmount; return savingsDepositAmount;
} }
public EnumOptionData getSavingProductType() { public EnumOptionData getSavingProductType() {
return savingProductType; return savingProductType;
} }
public EnumOptionData getTenureType() { public EnumOptionData getTenureType() {
return tenureType; return tenureType;
} }
public Integer getTenure() { public Integer getTenure() {
return tenure; return tenure;
} }
public EnumOptionData getInterestType() { public EnumOptionData getInterestType() {
return interestType; return interestType;
} }
public EnumOptionData getInterestCalculationMethod() { public EnumOptionData getInterestCalculationMethod() {
return interestCalculationMethod; return interestCalculationMethod;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public BigDecimal getMinimumBalanceForWithdrawal() {
return minimumBalanceForWithdrawal; return minimumBalanceForWithdrawal;
} }
public boolean isPartialDepositAllowed() { public boolean isPartialDepositAllowed() {
return isPartialDepositAllowed; return isPartialDepositAllowed;
} }
public boolean isLockinPeriodAllowed() { public boolean isLockinPeriodAllowed() {
return isLockinPeriodAllowed; return isLockinPeriodAllowed;
} }
public Integer getLockinPeriod() { public Integer getLockinPeriod() {
return lockinPeriod; return lockinPeriod;
} }
public EnumOptionData getLockinPeriodType() { public EnumOptionData getLockinPeriodType() {
return lockinPeriodType; return lockinPeriodType;
} }
public DateTime getCreatedOn() { public DateTime getCreatedOn() {
return createdOn; return createdOn;
} }
public DateTime getLastModifedOn() { public DateTime getLastModifedOn() {
return lastModifedOn; return lastModifedOn;
} }
public List<CurrencyData> getCurrencyOptions() { public List<CurrencyData> getCurrencyOptions() {
return currencyOptions; return currencyOptions;
} }
public void setCurrencyOptions(List<CurrencyData> currencyOptions) { public void setCurrencyOptions(List<CurrencyData> currencyOptions) {
this.currencyOptions = currencyOptions; this.currencyOptions = currencyOptions;
} }
public EnumOptionData getSavingFrequencyType() { public EnumOptionData getSavingFrequencyType() {
return savingFrequencyType; return savingFrequencyType;
} }
public List<EnumOptionData> getSavingsProductTypeOptions() { public List<EnumOptionData> getSavingsProductTypeOptions() {
return savingsProductTypeOptions; return savingsProductTypeOptions;
} }
public List<EnumOptionData> getTenureTypeOptions() { public List<EnumOptionData> getTenureTypeOptions() {
return tenureTypeOptions; return tenureTypeOptions;
} }
public List<EnumOptionData> getSavingFrequencyOptions() { public List<EnumOptionData> getSavingFrequencyOptions() {
return savingFrequencyOptions; return savingFrequencyOptions;
} }
public List<EnumOptionData> getSavingsInterestTypeOptions() { public List<EnumOptionData> getSavingsInterestTypeOptions() {
return savingsInterestTypeOptions; return savingsInterestTypeOptions;
} }
public List<EnumOptionData> getLockinPeriodTypeOptions() { public List<EnumOptionData> getLockinPeriodTypeOptions() {
return lockinPeriodTypeOptions; return lockinPeriodTypeOptions;
} }
public List<EnumOptionData> getInterestCalculationOptions() { public List<EnumOptionData> getInterestCalculationOptions() {
return interestCalculationOptions; 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"), INVALID(0, "savingFrequencyType.invalid"), DAILY(1, "savingFrequencyType.daily"), MONTHLY(2, "savingFrequencyType.monthly"), QUATERLY(
DAILY(1,"savingFrequencyType.daily"), 3, "savingFrequencyType.quaterly"), HALFYEARLY(4, "savingFrequencyType.halfyearly"), YEARLY(5, "savingFrequencyType.yearly");
MONTHLY(2,"savingFrequencyType.monthly"),
QUATERLY(3,"savingFrequencyType.quaterly"),
HALFYEARLY(4,"savingFrequencyType.halfyearly"),
YEARLY(5,"savingFrequencyType.yearly");
private final Integer value; private final Integer value;
private final String code; private final String code;
private SavingFrequencyType(final Integer value,final String code) { private SavingFrequencyType(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() {
return code;
}
public static SavingFrequencyType fromInt(final Integer frequency) { public String getCode() {
return code;
}
SavingFrequencyType savingFrequencyType = SavingFrequencyType.INVALID; public static SavingFrequencyType fromInt(final Integer frequency) {
switch (frequency) {
case 1: SavingFrequencyType savingFrequencyType = SavingFrequencyType.INVALID;
savingFrequencyType = SavingFrequencyType.DAILY; switch (frequency) {
break; case 1:
case 2: savingFrequencyType = SavingFrequencyType.DAILY;
savingFrequencyType = SavingFrequencyType.MONTHLY; break;
break; case 2:
case 3: savingFrequencyType = SavingFrequencyType.MONTHLY;
savingFrequencyType = SavingFrequencyType.QUATERLY; break;
break; case 3:
case 4: savingFrequencyType = SavingFrequencyType.QUATERLY;
savingFrequencyType = SavingFrequencyType.HALFYEARLY; break;
break; case 4:
case 5: savingFrequencyType = SavingFrequencyType.HALFYEARLY;
savingFrequencyType = SavingFrequencyType.YEARLY; break;
break; case 5:
default: savingFrequencyType = SavingFrequencyType.YEARLY;
savingFrequencyType = SavingFrequencyType.INVALID; break;
break; default:
} savingFrequencyType = SavingFrequencyType.INVALID;
return savingFrequencyType; break;
} }
return savingFrequencyType;
}
} }
@@ -2,43 +2,42 @@ package org.mifosplatform.portfolio.savingsaccountproduct.domain;
public enum SavingInterestCalculationMethod { public enum SavingInterestCalculationMethod {
AVERAGEBAL(1,"savinginterest.calculation.method.averagebal"), AVERAGEBAL(1, "savinginterest.calculation.method.averagebal"), MINBAL(2, "savinginterest.calculation.method.minbal"), MONTHLYCOLLECTION(
MINBAL(2,"savinginterest.calculation.method.minbal"), 3, "savinginterest.calculation.method.monthlycllection"), INVALID(0, "savinginterest.calculation.method.invalid");
MONTHLYCOLLECTION(3,"savinginterest.calculation.method.monthlycllection"),
INVALID(0,"savinginterest.calculation.method.invalid");
private final Integer value; private final Integer value;
private final String code; private final String code;
private SavingInterestCalculationMethod(final Integer value,final String code) { private SavingInterestCalculationMethod(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 SavingInterestCalculationMethod fromInt(final Integer frequency) {
SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID; public static SavingInterestCalculationMethod fromInt(final Integer frequency) {
switch (frequency) {
case 1: SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID;
savingInterestCalculationMethod = SavingInterestCalculationMethod.AVERAGEBAL; switch (frequency) {
break; case 1:
case 2: savingInterestCalculationMethod = SavingInterestCalculationMethod.AVERAGEBAL;
savingInterestCalculationMethod = SavingInterestCalculationMethod.MINBAL; break;
break; case 2:
case 3: savingInterestCalculationMethod = SavingInterestCalculationMethod.MINBAL;
savingInterestCalculationMethod = SavingInterestCalculationMethod.MONTHLYCOLLECTION; break;
break; case 3:
default: savingInterestCalculationMethod = SavingInterestCalculationMethod.MONTHLYCOLLECTION;
savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID; break;
break; default:
} savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID;
return savingInterestCalculationMethod; break;
} }
return savingInterestCalculationMethod;
}
} }
@@ -19,40 +19,45 @@ import org.mifosplatform.useradministration.domain.AppUser;
@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) @Column(name = "name", nullable = false)
private String name; private String name;
@Column(name = "description") @Column(name = "description")
private String description; private String description;
@Column(name = "is_deleted", nullable=false) @Column(name = "is_deleted", nullable = false)
private boolean deleted = false; private boolean deleted = false;
@Embedded @Embedded
SavingProductRelatedDetail savingProductRelatedDetail; SavingProductRelatedDetail savingProductRelatedDetail;
protected SavingProduct() { protected SavingProduct() {
this.name = null; 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, public SavingProduct(final String name, final String description, final MonetaryCurrency currency, final BigDecimal interestRate,
final SavingProductType savingProductType, final TenureTypeEnum tenureType, final Integer tenure, final SavingFrequencyType savingFrequencyType, final BigDecimal minInterestRate, final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount,
final SavingsInterestType savingsInterestType, SavingInterestCalculationMethod savingInterestCalculationMethod, final BigDecimal minimumBalanceForWithdrawal, final SavingProductType savingProductType, final TenureTypeEnum tenureType, final Integer tenure,
final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType){ 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(); this.name = name.trim();
if (StringUtils.isNotBlank(description)) { if (StringUtils.isNotBlank(description)) {
this.description = description.trim(); this.description = description.trim();
} else { } else {
this.description = null; this.description = null;
} }
this.savingProductRelatedDetail = new SavingProductRelatedDetail(currency, interestRate, minInterestRate, maxInterestRate, savingsDepositAmount, savingProductType, tenureType, tenure, this.savingProductRelatedDetail = new SavingProductRelatedDetail(currency, interestRate, minInterestRate, maxInterestRate,
savingFrequencyType, savingsInterestType, savingInterestCalculationMethod, minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType); savingsDepositAmount, savingProductType, tenureType, tenure, savingFrequencyType, savingsInterestType,
} savingInterestCalculationMethod, minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod,
lockinPeriodType);
}
public String getName() { public String getName() {
return this.name; return this.name;
} }
@@ -60,40 +65,40 @@ public class SavingProduct extends AbstractAuditableCustom<AppUser, Long> {
return this.description; return this.description;
} }
public MonetaryCurrency getCurrency() { public MonetaryCurrency getCurrency() {
return this.savingProductRelatedDetail.getCurrency(); return this.savingProductRelatedDetail.getCurrency();
} }
public BigDecimal getInterestRate(){ public BigDecimal getInterestRate() {
return this.savingProductRelatedDetail.getInterestRate(); return this.savingProductRelatedDetail.getInterestRate();
} }
public BigDecimal getMinimumBalance(){ public BigDecimal getMinimumBalance() {
return this.savingProductRelatedDetail.getMinimumBalance(); return this.savingProductRelatedDetail.getMinimumBalance();
} }
public boolean isDeleted() { public boolean isDeleted() {
return deleted; return deleted;
} }
public void delete() { public void delete() {
this.deleted = true; this.deleted = true;
} }
public SavingProductRelatedDetail getSavingProductRelatedDetail() { public SavingProductRelatedDetail getSavingProductRelatedDetail() {
return savingProductRelatedDetail; return savingProductRelatedDetail;
} }
public void update(final SavingProductCommand command) { public void update(final SavingProductCommand command) {
if (command.isNameChanged()) { if (command.isNameChanged()) {
this.name = command.getName(); this.name = command.getName();
} }
if (command.isDescriptionChanged()) { if (command.isDescriptionChanged()) {
this.description = command.getDescription(); this.description = command.getDescription();
} }
this.savingProductRelatedDetail.update(command); this.savingProductRelatedDetail.update(command);
} }
} }
@@ -14,213 +14,211 @@ import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum;
@Embeddable @Embeddable
public class SavingProductRelatedDetail { public class SavingProductRelatedDetail {
@Embedded @Embedded
private MonetaryCurrency currency; private MonetaryCurrency currency;
@Column(name = "interest_rate", scale = 6, precision = 19, nullable = false) @Column(name = "interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal interestRate; private BigDecimal interestRate;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Column(name = "min_interest_rate", scale = 6, precision = 19, nullable = false) @Column(name = "min_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal minInterestRate; private BigDecimal minInterestRate;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Column(name = "max_interest_rate", scale = 6, precision = 19, nullable = false) @Column(name = "max_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal maxInterestRate; private BigDecimal maxInterestRate;
@Column(name = "savings_deposit_amount", scale = 6, precision = 19, nullable = false) @Column(name = "savings_deposit_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal savingsDepositAmount; private BigDecimal savingsDepositAmount;
@Column(name = "savings_product_type", nullable=false) @Column(name = "savings_product_type", nullable = false)
private SavingProductType savingProductType; private SavingProductType savingProductType;
@Column(name = "tenure_type", nullable=false) @Column(name = "tenure_type", nullable = false)
private TenureTypeEnum tenureType; private TenureTypeEnum tenureType;
@Column(name = "tenure", nullable=false) @Column(name = "tenure", nullable = false)
private Integer tenure; private Integer tenure;
@Column(name = "frequency", nullable=false) @Column(name = "frequency", nullable = false)
private SavingFrequencyType frequency; private SavingFrequencyType frequency;
@Column(name = "interest_type", nullable=false) @Column(name = "interest_type", nullable = false)
private SavingsInterestType interestType; private SavingsInterestType interestType;
@Column(name = "interest_calculation_method") @Column(name = "interest_calculation_method")
private SavingInterestCalculationMethod interestCalculationMethod; private SavingInterestCalculationMethod interestCalculationMethod;
@Column(name = "min_bal_for_withdrawal", scale = 6, precision = 19, nullable = false) @Column(name = "min_bal_for_withdrawal", scale = 6, precision = 19, nullable = false)
private BigDecimal minimumBalanceForWithdrawal; private BigDecimal minimumBalanceForWithdrawal;
@Column(name = "is_partial_deposit_allowed", nullable=false) @Column(name = "is_partial_deposit_allowed", nullable = false)
private boolean isPartialDepositAllowed; private boolean isPartialDepositAllowed;
@Column(name = "is_lock_in_period_allowed", nullable=false) @Column(name = "is_lock_in_period_allowed", nullable = false)
private boolean isLockinPeriodAllowed; private boolean isLockinPeriodAllowed;
@Column(name = "lock_in_period", nullable=false) @Column(name = "lock_in_period", nullable = false)
private Integer lockinPeriod; private Integer lockinPeriod;
@Column(name = "lock_in_period_type", nullable=false) @Column(name = "lock_in_period_type", nullable = false)
private PeriodFrequencyType lockinPeriodType; private PeriodFrequencyType lockinPeriodType;
public SavingProductRelatedDetail() { public SavingProductRelatedDetail() {
this.interestRate=null; this.interestRate = null;
this.savingsDepositAmount=null; this.savingsDepositAmount = null;
} }
public SavingProductRelatedDetail(final MonetaryCurrency currency,final BigDecimal interestRate, final BigDecimal minInterestRate, final BigDecimal maxInterestRate, public SavingProductRelatedDetail(final MonetaryCurrency currency, final BigDecimal interestRate, final BigDecimal minInterestRate,
final BigDecimal savingsDepositAmount, final SavingProductType savingProductType, final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount, final SavingProductType savingProductType,
final TenureTypeEnum tenureType, final Integer tenure, final TenureTypeEnum tenureType, final Integer tenure, final SavingFrequencyType frequency,
final SavingFrequencyType frequency, final SavingsInterestType interestType, final SavingsInterestType interestType, final SavingInterestCalculationMethod interestCalculationMethod,
final SavingInterestCalculationMethod interestCalculationMethod, final BigDecimal minimumBalanceForWithdrawal, final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed,
final BigDecimal minimumBalanceForWithdrawal, final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType) {
final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed, this.currency = currency;
final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType) { this.interestRate = interestRate;
this.currency=currency; this.minInterestRate = minInterestRate;
this.interestRate=interestRate; this.maxInterestRate = maxInterestRate;
this.minInterestRate = minInterestRate; this.savingsDepositAmount = savingsDepositAmount;
this.maxInterestRate = maxInterestRate; this.savingProductType = savingProductType;
this.savingsDepositAmount=savingsDepositAmount; this.tenureType = tenureType;
this.savingProductType=savingProductType; this.tenure = tenure;
this.tenureType=tenureType; this.frequency = frequency;
this.tenure=tenure; this.interestType = interestType;
this.frequency=frequency; this.interestCalculationMethod = interestCalculationMethod;
this.interestType=interestType; this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal;
this.interestCalculationMethod=interestCalculationMethod; this.isPartialDepositAllowed = isPartialDepositAllowed;
this.minimumBalanceForWithdrawal=minimumBalanceForWithdrawal; this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.isPartialDepositAllowed=isPartialDepositAllowed; this.lockinPeriod = lockinPeriod;
this.isLockinPeriodAllowed=isLockinPeriodAllowed; this.lockinPeriodType = lockinPeriodType;
this.lockinPeriod=lockinPeriod; }
this.lockinPeriodType=lockinPeriodType;
}
public MonetaryCurrency getCurrency() { public MonetaryCurrency getCurrency() {
return this.currency.copy(); return this.currency.copy();
} }
public BigDecimal getInterestRate() { public BigDecimal getInterestRate() {
return BigDecimal.valueOf(Double.valueOf(this.interestRate.stripTrailingZeros().toString())); return BigDecimal.valueOf(Double.valueOf(this.interestRate.stripTrailingZeros().toString()));
} }
public BigDecimal getMinimumBalance(){ public BigDecimal getMinimumBalance() {
return BigDecimal.valueOf(Double.valueOf(this.savingsDepositAmount.stripTrailingZeros().toString())); return BigDecimal.valueOf(Double.valueOf(this.savingsDepositAmount.stripTrailingZeros().toString()));
} }
public void update(SavingProductCommand command){ public void update(SavingProductCommand command) {
Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal(); Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal();
if (command.isDigitsAfterDecimalChanged()) { if (command.isDigitsAfterDecimalChanged()) {
digitsAfterDecimal = command.getDigitsAfterDecimal(); digitsAfterDecimal = command.getDigitsAfterDecimal();
} }
String currencyCodeChanged = this.currency.getCode(); String currencyCodeChanged = this.currency.getCode();
if (command.isCurrencyCodeChanged()) { if (command.isCurrencyCodeChanged()) {
currencyCodeChanged = command.getCurrencyCode(); currencyCodeChanged = command.getCurrencyCode();
} }
if (command.isDigitsAfterDecimalChanged() || command.isCurrencyCodeChanged()) { if (command.isDigitsAfterDecimalChanged() || command.isCurrencyCodeChanged()) {
this.currency = new MonetaryCurrency(currencyCodeChanged, digitsAfterDecimal); this.currency = new MonetaryCurrency(currencyCodeChanged, digitsAfterDecimal);
} }
if (command.isInterestRateChanged()) { if (command.isInterestRateChanged()) {
this.interestRate = command.getInterestRate(); this.interestRate = command.getInterestRate();
} }
if(command.isSavingsDepositAmountChanged()){ if (command.isSavingsDepositAmountChanged()) {
this.savingsDepositAmount=command.getSavingsDepositAmount(); this.savingsDepositAmount = command.getSavingsDepositAmount();
} }
if (command.isSavingProductTypeChanged()) { if (command.isSavingProductTypeChanged()) {
this.savingProductType=SavingProductType.fromInt(command.getSavingProductType()); this.savingProductType = SavingProductType.fromInt(command.getSavingProductType());
} }
if(command.isTenureTypeChanged()){ if (command.isTenureTypeChanged()) {
this.tenureType=TenureTypeEnum.fromInt(command.getTenureType()); this.tenureType = TenureTypeEnum.fromInt(command.getTenureType());
} }
if (command.isTenureChanged()) { if (command.isTenureChanged()) {
this.tenure = command.getTenure(); this.tenure = command.getTenure();
} }
if (command.isFrequencyChanged()){ if (command.isFrequencyChanged()) {
this.frequency = SavingFrequencyType.fromInt(command.getFrequency()); this.frequency = SavingFrequencyType.fromInt(command.getFrequency());
} }
if (command.isInterestTypeChanged()) { if (command.isInterestTypeChanged()) {
this.interestType = SavingsInterestType.fromInt(command.getInterestType()); this.interestType = SavingsInterestType.fromInt(command.getInterestType());
} }
if (command.isInterestCalculationMethodChanged()){ if (command.isInterestCalculationMethodChanged()) {
this.interestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod()); this.interestCalculationMethod = SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod());
} }
if (command.isMinimumBalanceForWithdrawalChanged()) { if (command.isMinimumBalanceForWithdrawalChanged()) {
this.minimumBalanceForWithdrawal = command.getMinimumBalanceForWithdrawal(); this.minimumBalanceForWithdrawal = command.getMinimumBalanceForWithdrawal();
} }
if (command.isPartialDepositAllowedChanged()) { if (command.isPartialDepositAllowedChanged()) {
this.isPartialDepositAllowed = command.isPartialDepositAllowed(); this.isPartialDepositAllowed = command.isPartialDepositAllowed();
} }
if (command.isLockinPeriodAllowedChanged()){ if (command.isLockinPeriodAllowedChanged()) {
this.isLockinPeriodAllowed = command.isLockinPeriodAllowed(); this.isLockinPeriodAllowed = command.isLockinPeriodAllowed();
} }
if (command.isLockinPeriodChanged()){ if (command.isLockinPeriodChanged()) {
this.lockinPeriod = command.getLockinPeriod(); this.lockinPeriod = command.getLockinPeriod();
} }
if (command.isLockinPeriodTypeChanged()){ if (command.isLockinPeriodTypeChanged()) {
this.lockinPeriodType=PeriodFrequencyType.fromInt(command.getLockinPeriodType()); this.lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
} }
} }
public BigDecimal getSavingsDepositAmount() { public BigDecimal getSavingsDepositAmount() {
return savingsDepositAmount; return savingsDepositAmount;
} }
public SavingProductType getSavingProductType() { public SavingProductType getSavingProductType() {
return savingProductType; return savingProductType;
} }
public TenureTypeEnum getTenureType() { public TenureTypeEnum getTenureType() {
return tenureType; return tenureType;
} }
public Integer getTenure() { public Integer getTenure() {
return tenure; return tenure;
} }
public SavingFrequencyType getFrequency() { public SavingFrequencyType getFrequency() {
return frequency; return frequency;
} }
public SavingsInterestType getInterestType() { public SavingsInterestType getInterestType() {
return interestType; return interestType;
} }
public SavingInterestCalculationMethod getInterestCalculationMethod() { public SavingInterestCalculationMethod getInterestCalculationMethod() {
return interestCalculationMethod; return interestCalculationMethod;
} }
public BigDecimal getMinimumBalanceForWithdrawal() { public BigDecimal getMinimumBalanceForWithdrawal() {
return minimumBalanceForWithdrawal; return minimumBalanceForWithdrawal;
} }
public boolean isPartialDepositAllowed() { public boolean isPartialDepositAllowed() {
return isPartialDepositAllowed; return isPartialDepositAllowed;
} }
public boolean isLockinPeriodAllowed() { public boolean isLockinPeriodAllowed() {
return isLockinPeriodAllowed; return isLockinPeriodAllowed;
} }
public Integer getLockinPeriod() { public Integer getLockinPeriod() {
return lockinPeriod; return lockinPeriod;
} }
public PeriodFrequencyType getLockinPeriodType() { public PeriodFrequencyType getLockinPeriodType() {
return lockinPeriodType; 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"), INVALID(0, "savingProductType.invalid"), RECCURING(1, "savingProductType.reccuring"), REGULAR(2, "savingProductType.regular");
RECCURING(1,"savingProductType.reccuring"),
REGULAR(2,"savingProductType.regular");
private final Integer value; private final Integer value;
private final String code; private final String code;
private SavingProductType(final Integer value,final String code) { private SavingProductType(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() {
return code;
}
public static SavingProductType fromInt(final Integer frequency) { public String getCode() {
return code;
}
SavingProductType savingProductType = SavingProductType.INVALID; public static SavingProductType fromInt(final Integer frequency) {
switch (frequency) {
case 1:
savingProductType = SavingProductType.RECCURING;
break;
case 2:
savingProductType = SavingProductType.REGULAR;
break;
default:
savingProductType = SavingProductType.INVALID;
break;
}
return savingProductType;
}
public boolean isReccuring(){ SavingProductType savingProductType = SavingProductType.INVALID;
return this.value.equals(SavingProductType.RECCURING.getValue()); switch (frequency) {
} case 1:
savingProductType = SavingProductType.RECCURING;
break;
case 2:
savingProductType = SavingProductType.REGULAR;
break;
default:
savingProductType = SavingProductType.INVALID;
break;
}
return savingProductType;
}
public boolean isRegular(){ public boolean isReccuring() {
return this.value.equals(SavingProductType.REGULAR.getValue()); 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"), INVALID(0, "savingsInterestType.invalid"), SIMPLE(1, "savingsInterestType.simple"), COMPOUNDING(2, "savingsInterestType.compounding");
SIMPLE(1,"savingsInterestType.simple"),
COMPOUNDING(2,"savingsInterestType.compounding");
private final Integer value; private final Integer value;
private final String code; private final String code;
private SavingsInterestType(final Integer value,final String code) { private SavingsInterestType(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() {
return code;
}
public static SavingsInterestType fromInt(final Integer frequency) { public String getCode() {
return code;
}
SavingsInterestType savingsInterestType = SavingsInterestType.INVALID; public static SavingsInterestType fromInt(final Integer frequency) {
switch (frequency) {
case 1: SavingsInterestType savingsInterestType = SavingsInterestType.INVALID;
savingsInterestType = SavingsInterestType.SIMPLE; switch (frequency) {
break; case 1:
case 2: savingsInterestType = SavingsInterestType.SIMPLE;
savingsInterestType = SavingsInterestType.COMPOUNDING; break;
break; case 2:
default: savingsInterestType = SavingsInterestType.COMPOUNDING;
savingsInterestType = SavingsInterestType.INVALID; break;
break; default:
} savingsInterestType = SavingsInterestType.INVALID;
return savingsInterestType; 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() { public String getCode() {
return code; return code;
} }
public static SavingsLockinPeriodEnum fromInt(final Integer frequency) { 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;
}
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) {
super("error.msg.savingproduct.id.invalid", "Saving product with identifier " + id + " does not exist", id);
}
public SavingProductNotFoundException(Long id) {
super("error.msg.savingproduct.id.invalid", "Saving product with identifier " + id + " does not exist", id);
}
} }
@@ -10,76 +10,88 @@ import org.mifosplatform.portfolio.savingsaccountproduct.command.SavingProductCo
public class SavingProductCommandValidator { public class SavingProductCommandValidator {
private final SavingProductCommand command; private final SavingProductCommand command;
public SavingProductCommandValidator(final SavingProductCommand command) { public SavingProductCommandValidator(final SavingProductCommand command) {
this.command=command; this.command = command;
} }
public void validateForUpdate() { public void validateForUpdate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsproduct"); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsproduct");
baseDataValidator.reset().parameter("id").value(command.getId()).notNull(); baseDataValidator.reset().parameter("id").value(command.getId()).notNull();
baseDataValidator.reset().parameter("name").value(command.getName()).ignoreIfNull().notBlank(); baseDataValidator.reset().parameter("name").value(command.getName()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("description").value(command.getDescription()).ignoreIfNull().notExceedingLengthOf(500); baseDataValidator.reset().parameter("description").value(command.getDescription()).ignoreIfNull().notExceedingLengthOf(500);
baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).ignoreIfNull().notBlank(); baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).ignoreIfNull().inMinMaxRange(0, 6); baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).ignoreIfNull().inMinMaxRange(0, 6);
baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).ignoreIfNull().notBlank(); baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).ignoreIfNull().notBlank(); baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).ignoreIfNull().notBlank(); baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).ignoreIfNull().notBlank();
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate()); baseDataValidator.reset().parameter("minInterestRate")
baseDataValidator.reset().parameter("interestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate()); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate()); baseDataValidator.reset().parameter("interestRate")
baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).ignoreIfNull().zeroOrPositiveAmount(); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).ignoreIfNull(); baseDataValidator.reset().parameter("minInterestRate")
baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).ignoreIfNull(); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate());
baseDataValidator.reset().parameter("tenure").value(command.getTenure()).ignoreIfNull(); baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).ignoreIfNull()
baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).ignoreIfNull(); .zeroOrPositiveAmount();
baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).ignoreIfNull(); baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).ignoreIfNull();
baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).ignoreIfNull(); baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).ignoreIfNull();
baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).ignoreIfNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("tenure").value(command.getTenure()).ignoreIfNull();
baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed()).trueOrFalseRequired(command.isPartialDepositAllowedChanged()).ignoreIfNull(); baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).ignoreIfNull();
baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed()).trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).ignoreIfNull(); baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).ignoreIfNull();
baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).ignoreIfNull(); baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).ignoreIfNull();
baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).ignoreIfNull(); baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).ignoreIfNull()
.zeroOrPositiveAmount();
baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed())
.trueOrFalseRequired(command.isPartialDepositAllowedChanged()).ignoreIfNull();
baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed())
.trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).ignoreIfNull();
baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).ignoreIfNull();
baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).ignoreIfNull();
if (!dataValidationErrors.isEmpty()) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); "Validation errors exist.", dataValidationErrors); }
} }
}
public void validateForCreate() { public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("product"); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("product");
baseDataValidator.reset().parameter("name").value(command.getName()).notBlank(); baseDataValidator.reset().parameter("name").value(command.getName()).notBlank();
baseDataValidator.reset().parameter("description").value(command.getDescription()).notExceedingLengthOf(500); baseDataValidator.reset().parameter("description").value(command.getDescription()).notExceedingLengthOf(500);
baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).notBlank(); baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).notBlank();
baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).notNull().inMinMaxRange(0, 6); baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).notNull().inMinMaxRange(0, 6);
baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("interestRate").value(command.getInterestRate()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("minInterestRate").value(command.getMinInterestRate()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("maxInterestRate").value(command.getMaxInterestRate()).notNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate()); baseDataValidator.reset().parameter("minInterestRate")
baseDataValidator.reset().parameter("interestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate()); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate()); baseDataValidator.reset().parameter("interestRate")
baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).notNull().zeroOrPositiveAmount(); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getInterestRate(), command.getMaxInterestRate());
baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).notNull(); baseDataValidator.reset().parameter("minInterestRate")
baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).notNull(); .comapareMinAndMaxOfTwoBigDecmimalNos(command.getMinInterestRate(), command.getInterestRate());
baseDataValidator.reset().parameter("tenure").value(command.getTenure()).notNull(); baseDataValidator.reset().parameter("savingsDepositAmount").value(command.getSavingsDepositAmount()).notNull()
baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).notNull(); .zeroOrPositiveAmount();
baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).notNull(); baseDataValidator.reset().parameter("savingProductType").value(command.getSavingProductType()).notNull();
baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).notNull(); baseDataValidator.reset().parameter("tenureType").value(command.getTenureType()).notNull();
baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(command.getMinimumBalanceForWithdrawal()).notNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("tenure").value(command.getTenure()).notNull();
baseDataValidator.reset().parameter("isPartialDepositAllowed").value(command.isPartialDepositAllowed()).trueOrFalseRequired(command.isPartialDepositAllowedChanged()).notNull(); baseDataValidator.reset().parameter("frequency").value(command.getFrequency()).notNull();
baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(command.isLockinPeriodAllowed()).trueOrFalseRequired(command.isLockinPeriodAllowedChanged()).notNull(); baseDataValidator.reset().parameter("interestType").value(command.getInterestType()).notNull();
baseDataValidator.reset().parameter("lockinPeriod").value(command.getLockinPeriod()).notNull(); baseDataValidator.reset().parameter("interestCalculationMethod").value(command.getInterestCalculationMethod()).notNull();
baseDataValidator.reset().parameter("lockinPeriodType").value(command.getLockinPeriodType()).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()) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); "Validation errors exist.", dataValidationErrors); }
} }
}
} }
@@ -10,154 +10,180 @@ import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum;
public class SavingProductEnumerations { public class SavingProductEnumerations {
public static EnumOptionData savingProductType(final int id) { public static EnumOptionData savingProductType(final int id) {
return savingProductType(SavingProductType.fromInt(id)); return savingProductType(SavingProductType.fromInt(id));
} }
public static EnumOptionData tenureTypeEnum(final int id) { public static EnumOptionData tenureTypeEnum(final int id) {
return tenureTypeEnum(TenureTypeEnum.fromInt(id)); return tenureTypeEnum(TenureTypeEnum.fromInt(id));
} }
public static EnumOptionData interestFrequencyType(final int id) { public static EnumOptionData interestFrequencyType(final int id) {
return interestFrequencyType(SavingFrequencyType.fromInt(id)); return interestFrequencyType(SavingFrequencyType.fromInt(id));
} }
public static EnumOptionData savingInterestType(final int id) { public static EnumOptionData savingInterestType(final int id) {
return savingInterestType(SavingsInterestType.fromInt(id)); return savingInterestType(SavingsInterestType.fromInt(id));
} }
public static EnumOptionData savingInterestCalculationMethod(final int id) { public static EnumOptionData savingInterestCalculationMethod(final int id) {
return savingInterestCalculationMethod(SavingInterestCalculationMethod.fromInt(id)); return savingInterestCalculationMethod(SavingInterestCalculationMethod.fromInt(id));
} }
public static EnumOptionData savingsLockinPeriod(final int id){ public static EnumOptionData savingsLockinPeriod(final int id) {
return savingsLockinPeriod(SavingsLockinPeriodEnum.fromInt(id)); return savingsLockinPeriod(SavingsLockinPeriodEnum.fromInt(id));
} }
public static EnumOptionData savingsLockinPeriod(SavingsLockinPeriodEnum type) { public static EnumOptionData savingsLockinPeriod(SavingsLockinPeriodEnum type) {
final String codePrefix = "savings.product."; final String codePrefix = "savings.product.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case DAYS: case DAYS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.DAYS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.DAYS.getCode(), "Days"); optionData = new EnumOptionData(SavingsLockinPeriodEnum.DAYS.getValue().longValue(), codePrefix
break; + SavingsLockinPeriodEnum.DAYS.getCode(), "Days");
case MONTHS: break;
optionData = new EnumOptionData(SavingsLockinPeriodEnum.MONTHS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.MONTHS.getCode(), "Months"); case MONTHS:
break; optionData = new EnumOptionData(SavingsLockinPeriodEnum.MONTHS.getValue().longValue(), codePrefix
case WEEKS: + SavingsLockinPeriodEnum.MONTHS.getCode(), "Months");
optionData = new EnumOptionData(SavingsLockinPeriodEnum.WEEKS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.WEEKS.getCode(), "Weeks"); break;
break; case WEEKS:
case YEARS: optionData = new EnumOptionData(SavingsLockinPeriodEnum.WEEKS.getValue().longValue(), codePrefix
optionData = new EnumOptionData(SavingsLockinPeriodEnum.YEARS.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.YEARS.getCode(), "Years"); + SavingsLockinPeriodEnum.WEEKS.getCode(), "Weeks");
break; break;
default: case YEARS:
optionData = new EnumOptionData(SavingsLockinPeriodEnum.INVALID.getValue().longValue(), codePrefix+SavingsLockinPeriodEnum.INVALID.getCode(), "Invalid"); optionData = new EnumOptionData(SavingsLockinPeriodEnum.YEARS.getValue().longValue(), codePrefix
break; + SavingsLockinPeriodEnum.YEARS.getCode(), "Years");
} break;
return optionData; 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 savingInterestCalculationMethod(SavingInterestCalculationMethod type) {
final String codePrefix = "savings.interestCalculation.method."; final String codePrefix = "savings.interestCalculation.method.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case MINBAL: case MINBAL:
optionData = new EnumOptionData(SavingInterestCalculationMethod.MINBAL.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.MINBAL.getCode(), "Minimumbalance"); optionData = new EnumOptionData(SavingInterestCalculationMethod.MINBAL.getValue().longValue(), codePrefix
break; + SavingInterestCalculationMethod.MINBAL.getCode(), "Minimumbalance");
case AVERAGEBAL: break;
optionData = new EnumOptionData(SavingInterestCalculationMethod.AVERAGEBAL.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.AVERAGEBAL.getCode(), "AverageBalance"); case AVERAGEBAL:
break; optionData = new EnumOptionData(SavingInterestCalculationMethod.AVERAGEBAL.getValue().longValue(), codePrefix
case INVALID: + SavingInterestCalculationMethod.AVERAGEBAL.getCode(), "AverageBalance");
optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.INVALID.getCode(), "Invalid"); break;
break; case INVALID:
case MONTHLYCOLLECTION: optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix
optionData = new EnumOptionData(SavingInterestCalculationMethod.MONTHLYCOLLECTION.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.MONTHLYCOLLECTION.getCode(), "MonthlyCollection"); + SavingInterestCalculationMethod.INVALID.getCode(), "Invalid");
break; break;
default: case MONTHLYCOLLECTION:
optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix+SavingInterestCalculationMethod.INVALID.getCode(), "Invalid"); optionData = new EnumOptionData(SavingInterestCalculationMethod.MONTHLYCOLLECTION.getValue().longValue(), codePrefix
break; + SavingInterestCalculationMethod.MONTHLYCOLLECTION.getCode(), "MonthlyCollection");
} break;
return optionData; 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 savingInterestType(SavingsInterestType type) {
final String codePrefix = "savings.interest.type."; final String codePrefix = "savings.interest.type.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case COMPOUNDING: case COMPOUNDING:
optionData = new EnumOptionData(SavingsInterestType.COMPOUNDING.getValue().longValue(), codePrefix+SavingsInterestType.COMPOUNDING.getCode(), "Compounding"); optionData = new EnumOptionData(SavingsInterestType.COMPOUNDING.getValue().longValue(), codePrefix
break; + SavingsInterestType.COMPOUNDING.getCode(), "Compounding");
case SIMPLE: break;
optionData = new EnumOptionData(SavingsInterestType.SIMPLE.getValue().longValue(), codePrefix+SavingsInterestType.SIMPLE.getCode(), "Simple"); case SIMPLE:
break; optionData = new EnumOptionData(SavingsInterestType.SIMPLE.getValue().longValue(), codePrefix
default: + SavingsInterestType.SIMPLE.getCode(), "Simple");
optionData = new EnumOptionData(SavingsInterestType.INVALID.getValue().longValue(), codePrefix+SavingsInterestType.INVALID.getCode(), "Invalid"); break;
break; default:
} optionData = new EnumOptionData(SavingsInterestType.INVALID.getValue().longValue(), codePrefix
return optionData; + SavingsInterestType.INVALID.getCode(), "Invalid");
} break;
}
return optionData;
}
public static EnumOptionData interestFrequencyType(SavingFrequencyType type) { public static EnumOptionData interestFrequencyType(SavingFrequencyType type) {
final String codePrefix = "saving.product.frequency.period."; final String codePrefix = "saving.product.frequency.period.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case DAILY: case DAILY:
optionData = new EnumOptionData(SavingFrequencyType.DAILY.getValue().longValue(), codePrefix + SavingFrequencyType.DAILY.getCode(), "Days"); optionData = new EnumOptionData(SavingFrequencyType.DAILY.getValue().longValue(), codePrefix
break; + SavingFrequencyType.DAILY.getCode(), "Days");
case MONTHLY: break;
optionData = new EnumOptionData(SavingFrequencyType.MONTHLY.getValue().longValue(), codePrefix + SavingFrequencyType.MONTHLY.getCode(), "Weeks"); case MONTHLY:
break; optionData = new EnumOptionData(SavingFrequencyType.MONTHLY.getValue().longValue(), codePrefix
case QUATERLY: + SavingFrequencyType.MONTHLY.getCode(), "Weeks");
optionData = new EnumOptionData(SavingFrequencyType.QUATERLY.getValue().longValue(), codePrefix + SavingFrequencyType.QUATERLY.getCode(), "Months"); break;
break; case QUATERLY:
case HALFYEARLY: optionData = new EnumOptionData(SavingFrequencyType.QUATERLY.getValue().longValue(), codePrefix
optionData = new EnumOptionData(SavingFrequencyType.HALFYEARLY.getValue().longValue(), codePrefix + SavingFrequencyType.HALFYEARLY.getCode(), "Months"); + SavingFrequencyType.QUATERLY.getCode(), "Months");
break; break;
case YEARLY: case HALFYEARLY:
optionData = new EnumOptionData(SavingFrequencyType.YEARLY.getValue().longValue(), codePrefix + SavingFrequencyType.YEARLY.getCode(), "Yearly"); optionData = new EnumOptionData(SavingFrequencyType.HALFYEARLY.getValue().longValue(), codePrefix
break; + SavingFrequencyType.HALFYEARLY.getCode(), "Months");
default: break;
optionData = new EnumOptionData(SavingFrequencyType.INVALID.getValue().longValue(), SavingFrequencyType.INVALID.getCode(), "Invalid"); case YEARLY:
break; optionData = new EnumOptionData(SavingFrequencyType.YEARLY.getValue().longValue(), codePrefix
} + SavingFrequencyType.YEARLY.getCode(), "Yearly");
return optionData; 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 tenureTypeEnum(final TenureTypeEnum type) {
final String codePrefix = "savings.tenure."; final String codePrefix = "savings.tenure.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case FIXED_PERIOD: case FIXED_PERIOD:
optionData = new EnumOptionData(TenureTypeEnum.FIXED_PERIOD.getValue().longValue(), codePrefix+TenureTypeEnum.FIXED_PERIOD.getCode(), "FixedPeriod"); optionData = new EnumOptionData(TenureTypeEnum.FIXED_PERIOD.getValue().longValue(), codePrefix
break; + TenureTypeEnum.FIXED_PERIOD.getCode(), "FixedPeriod");
case PERPETUAL: break;
optionData = new EnumOptionData(TenureTypeEnum.PERPETUAL.getValue().longValue(), codePrefix+TenureTypeEnum.PERPETUAL.getCode(), "Perpetual"); case PERPETUAL:
break; optionData = new EnumOptionData(TenureTypeEnum.PERPETUAL.getValue().longValue(), codePrefix
default: + TenureTypeEnum.PERPETUAL.getCode(), "Perpetual");
optionData = new EnumOptionData(TenureTypeEnum.INVALID.getValue().longValue(), codePrefix+TenureTypeEnum.INVALID.getCode(), "Invalid"); break;
break; default:
} optionData = new EnumOptionData(TenureTypeEnum.INVALID.getValue().longValue(), codePrefix
return optionData; + TenureTypeEnum.INVALID.getCode(), "Invalid");
} break;
}
return optionData;
}
public static EnumOptionData savingProductType(final SavingProductType type) { public static EnumOptionData savingProductType(final SavingProductType type) {
final String codePrefix = "savings.product."; final String codePrefix = "savings.product.";
EnumOptionData optionData = null; EnumOptionData optionData = null;
switch (type) { switch (type) {
case RECCURING: case RECCURING:
optionData = new EnumOptionData(SavingProductType.RECCURING.getValue().longValue(), codePrefix + SavingProductType.RECCURING.getCode(), "Reccuring"); optionData = new EnumOptionData(SavingProductType.RECCURING.getValue().longValue(), codePrefix
break; + SavingProductType.RECCURING.getCode(), "Reccuring");
case REGULAR: break;
optionData = new EnumOptionData(SavingProductType.REGULAR.getValue().longValue(), codePrefix + SavingProductType.REGULAR.getCode(), "Regular"); case REGULAR:
break; optionData = new EnumOptionData(SavingProductType.REGULAR.getValue().longValue(), codePrefix
case INVALID: + SavingProductType.REGULAR.getCode(), "Regular");
optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), codePrefix + SavingProductType.INVALID.getCode(), "Invalid"); break;
break; case INVALID:
default: optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), codePrefix
optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), SavingProductType.INVALID.getCode(), "Invalid"); + SavingProductType.INVALID.getCode(), "Invalid");
break; break;
} default:
return optionData; 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 PlatformSecurityContext context;
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final CurrencyReadPlatformService currencyReadPlatformService; private final CurrencyReadPlatformService currencyReadPlatformService;
@Autowired @Autowired
public SavingProductReadPlatformServiceImpl(final PlatformSecurityContext context,final TenantAwareRoutingDataSource dataSource,final CurrencyReadPlatformService currencyReadPlatformService) { public SavingProductReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final CurrencyReadPlatformService currencyReadPlatformService) {
this.context=context; this.context = context;
jdbcTemplate=new JdbcTemplate(dataSource); jdbcTemplate = new JdbcTemplate(dataSource);
this.currencyReadPlatformService=currencyReadPlatformService; this.currencyReadPlatformService = currencyReadPlatformService;
} }
@Override @Override
public Collection<SavingProductData> retrieveAllSavingProducts() { public Collection<SavingProductData> retrieveAllSavingProducts() {
this.context.authenticatedUser(); this.context.authenticatedUser();
SavingProductMapper savingProductMapper=new SavingProductMapper(); SavingProductMapper savingProductMapper = new SavingProductMapper();
String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.is_deleted=0"; String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.is_deleted=0";
return this.jdbcTemplate.query(sql,savingProductMapper, new Object[]{}); return this.jdbcTemplate.query(sql, savingProductMapper, new Object[] {});
} }
@Override @Override
public Collection<SavingProductLookup> retrieveAllSavingProductsForLookup() { public Collection<SavingProductLookup> retrieveAllSavingProductsForLookup() {
this.context.authenticatedUser(); this.context.authenticatedUser();
SavingProductLookupMapper savingProductLookupMapper=new SavingProductLookupMapper(); SavingProductLookupMapper savingProductLookupMapper = new SavingProductLookupMapper();
String sql="select"+savingProductLookupMapper.savingProductLookupSchema(); String sql = "select" + savingProductLookupMapper.savingProductLookupSchema();
return this.jdbcTemplate.query(sql, savingProductLookupMapper, new Object[]{}); return this.jdbcTemplate.query(sql, savingProductLookupMapper, new Object[] {});
} }
@Override @Override
public SavingProductData retrieveSavingProduct(Long savingProductId) { public SavingProductData retrieveSavingProduct(Long savingProductId) {
try{ try {
this.context.authenticatedUser(); this.context.authenticatedUser();
SavingProductMapper savingProductMapper=new SavingProductMapper(); SavingProductMapper savingProductMapper = new SavingProductMapper();
String sql = "select " + savingProductMapper.savingProductSchema() String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.id = ? and sp.is_deleted=0";
+ " where sp.id = ? and sp.is_deleted=0"; SavingProductData productData = this.jdbcTemplate.queryForObject(sql, savingProductMapper, new Object[] { savingProductId });
SavingProductData productData = this.jdbcTemplate.queryForObject(sql,
savingProductMapper, new Object[] { savingProductId });
populateProductDataWithDropdownOptions(productData); populateProductDataWithDropdownOptions(productData);
return productData; return productData;
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
throw new LoanProductNotFoundException(savingProductId); throw new LoanProductNotFoundException(savingProductId);
} }
} }
@Override @Override
public SavingProductData retrieveNewSavingProductDetails() { public SavingProductData retrieveNewSavingProductDetails() {
SavingProductData productData=new SavingProductData(); SavingProductData productData = new SavingProductData();
populateProductDataWithDropdownOptions(productData); populateProductDataWithDropdownOptions(productData);
return productData; return productData;
} }
private static final class SavingProductMapper implements RowMapper<SavingProductData> { private static final class SavingProductMapper implements RowMapper<SavingProductData> {
public String savingProductSchema(){ 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, " 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.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.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.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.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, " + " 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" + "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"; + " from m_product_savings sp join m_currency curr on curr.code = sp.currency_code";
} }
@Override @Override
public SavingProductData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) public SavingProductData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
String name = rs.getString("name"); String name = rs.getString("name");
String description = rs.getString("description"); String description = rs.getString("description");
String currencyCode = rs.getString("currencyCode"); String currencyCode = rs.getString("currencyCode");
String currencyName = rs.getString("currencyName"); String currencyName = rs.getString("currencyName");
String currencyNameCode = rs.getString("currencyNameCode"); String currencyNameCode = rs.getString("currencyNameCode");
String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
Integer currencyDigits = JdbcSupport.getInteger(rs,"currencyDigits"); Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
CurrencyData currencyData = new CurrencyData(currencyCode,currencyName, currencyDigits, currencyDisplaySymbol,currencyNameCode); CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
BigDecimal interestRate = rs.getBigDecimal("interestRate"); currencyNameCode);
BigDecimal minInterestRate = rs.getBigDecimal("minInterestRate"); BigDecimal interestRate = rs.getBigDecimal("interestRate");
BigDecimal maxInterestRate = rs.getBigDecimal("maxInterstRate"); BigDecimal minInterestRate = rs.getBigDecimal("minInterestRate");
BigDecimal maxInterestRate = rs.getBigDecimal("maxInterstRate");
DateTime createdOn = JdbcSupport.getDateTime(rs, "createdon"); DateTime createdOn = JdbcSupport.getDateTime(rs, "createdon");
DateTime lastModifedOn = JdbcSupport.getDateTime(rs, "modifiedon"); DateTime lastModifedOn = JdbcSupport.getDateTime(rs, "modifiedon");
BigDecimal savingsDepositAmount=rs.getBigDecimal("savingsDepositAmount"); BigDecimal savingsDepositAmount = rs.getBigDecimal("savingsDepositAmount");
EnumOptionData savingProductTypeEnum=SavingProductEnumerations.savingProductType(SavingProductType.fromInt(JdbcSupport.getInteger(rs, "savingProductType"))); EnumOptionData savingProductTypeEnum = SavingProductEnumerations.savingProductType(SavingProductType.fromInt(JdbcSupport
EnumOptionData tenureTypeEnum = SavingProductEnumerations.tenureTypeEnum(JdbcSupport.getInteger(rs, "tenureType")); .getInteger(rs, "savingProductType")));
Integer tenure = JdbcSupport.getInteger(rs, "tenure"); EnumOptionData tenureTypeEnum = SavingProductEnumerations.tenureTypeEnum(JdbcSupport.getInteger(rs, "tenureType"));
EnumOptionData savingFrequencyType = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, "frequency")); Integer tenure = JdbcSupport.getInteger(rs, "tenure");
EnumOptionData savingInterestType = SavingProductEnumerations.savingInterestType(JdbcSupport.getInteger(rs, "interestType")); EnumOptionData savingFrequencyType = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, "frequency"));
EnumOptionData interestCalculationMethodEnum=SavingProductEnumerations.savingInterestCalculationMethod(JdbcSupport.getInteger(rs, "interestCalculationMethod")); EnumOptionData savingInterestType = SavingProductEnumerations.savingInterestType(JdbcSupport.getInteger(rs, "interestType"));
BigDecimal minimumBalanceForWithdrawal=rs.getBigDecimal("minimumBalanceForWithdrawal"); EnumOptionData interestCalculationMethodEnum = SavingProductEnumerations.savingInterestCalculationMethod(JdbcSupport
boolean isPartialDepositAllowed = rs.getBoolean("isPartialDepositAllowed"); .getInteger(rs, "interestCalculationMethod"));
boolean isLockinPeriodAllowed =rs.getBoolean("isLockinPeriodAllowed"); BigDecimal minimumBalanceForWithdrawal = rs.getBigDecimal("minimumBalanceForWithdrawal");
Integer lockinPeriod=JdbcSupport.getInteger(rs, "lockinPeriod"); boolean isPartialDepositAllowed = rs.getBoolean("isPartialDepositAllowed");
EnumOptionData lockinPeriodType= SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType.fromInt(JdbcSupport.getInteger(rs, "lockinPeriodType"))); 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, return new SavingProductData(createdOn, lastModifedOn, id, name, description, interestRate, minInterestRate, maxInterestRate,
savingProductTypeEnum, tenureTypeEnum, tenure, savingFrequencyType, savingInterestType, interestCalculationMethodEnum, currencyData, currencyDigits, savingsDepositAmount, savingProductTypeEnum, tenureTypeEnum, tenure, savingFrequencyType,
minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType); savingInterestType, interestCalculationMethodEnum, minimumBalanceForWithdrawal, isPartialDepositAllowed,
} isLockinPeriodAllowed, lockinPeriod, lockinPeriodType);
} }
}
private static final class SavingProductLookupMapper implements private static final class SavingProductLookupMapper implements RowMapper<SavingProductLookup> {
RowMapper<SavingProductLookup> {
public String savingProductLookupSchema() { public String savingProductLookupSchema() {
return "sp.id as id, sp.name as name from m_product_savings sp"; return "sp.id as id, sp.name as name from m_product_savings sp";
} }
@Override @Override
public SavingProductLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public SavingProductLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
String name = rs.getString("name"); String name = rs.getString("name");
return new SavingProductLookup(id, name); return new SavingProductLookup(id, name);
} }
} }
private void populateProductDataWithDropdownOptions(final SavingProductData productData) {
List<CurrencyData> currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies(); private void populateProductDataWithDropdownOptions(final SavingProductData productData) {
productData.setCurrencyOptions(currencyOptions);
} 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 @Autowired
public SavingProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final SavingProductRepository savingProductRepository) { public SavingProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context,
this.context=context; final SavingProductRepository savingProductRepository) {
this.savingProductRepository=savingProductRepository; this.context = context;
} this.savingProductRepository = savingProductRepository;
}
@Transactional @Transactional
@Override @Override
public EntityIdentifier createSavingProduct(final SavingProductCommand command) { public EntityIdentifier createSavingProduct(final SavingProductCommand command) {
this.context.authenticatedUser(); this.context.authenticatedUser();
SavingProductCommandValidator validator=new SavingProductCommandValidator(command); SavingProductCommandValidator validator = new SavingProductCommandValidator(command);
validator.validateForCreate(); validator.validateForCreate();
SavingProductType savingProductType = SavingProductType.fromInt(command.getSavingProductType()); SavingProductType savingProductType = SavingProductType.fromInt(command.getSavingProductType());
TenureTypeEnum tenureType = TenureTypeEnum.fromInt(command.getTenureType()); TenureTypeEnum tenureType = TenureTypeEnum.fromInt(command.getTenureType());
SavingFrequencyType savingFrequencyType=SavingFrequencyType.fromInt(command.getFrequency()); SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(command.getFrequency());
SavingsInterestType interestType = SavingsInterestType.fromInt(command.getInterestType()); SavingsInterestType interestType = SavingsInterestType.fromInt(command.getInterestType());
PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
SavingInterestCalculationMethod savingInterestCalculationMethod=SavingInterestCalculationMethod.fromInt(command.getInterestCalculationMethod()); SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(command
MonetaryCurrency currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal()); .getInterestCalculationMethod());
MonetaryCurrency currency = new MonetaryCurrency(command.getCurrencyCode(), command.getDigitsAfterDecimal());
SavingProduct product = new SavingProduct(command.getName(), command.getDescription(), currency, command.getInterestRate(), command.getMinInterestRate(), command.getMaxInterestRate(), SavingProduct product = new SavingProduct(command.getName(), command.getDescription(), currency, command.getInterestRate(),
command.getSavingsDepositAmount(), savingProductType, tenureType, command.getTenure(), savingFrequencyType, interestType, command.getMinInterestRate(), command.getMaxInterestRate(), command.getSavingsDepositAmount(), savingProductType,
savingInterestCalculationMethod, command.getMinimumBalanceForWithdrawal(), command.isPartialDepositAllowed(), tenureType, command.getTenure(), savingFrequencyType, interestType, savingInterestCalculationMethod,
command.isLockinPeriodAllowed(), command.getLockinPeriod(), lockinPeriodType); command.getMinimumBalanceForWithdrawal(), command.isPartialDepositAllowed(), command.isLockinPeriodAllowed(),
command.getLockinPeriod(), lockinPeriodType);
this.savingProductRepository.save(product); this.savingProductRepository.save(product);
return new EntityIdentifier(product.getId()); return new EntityIdentifier(product.getId());
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateSavingProduct(final SavingProductCommand command) { public EntityIdentifier updateSavingProduct(final SavingProductCommand command) {
this.context.authenticatedUser(); this.context.authenticatedUser();
SavingProductCommandValidator validator=new SavingProductCommandValidator(command); SavingProductCommandValidator validator = new SavingProductCommandValidator(command);
validator.validateForUpdate(); validator.validateForUpdate();
SavingProduct product=this.savingProductRepository.findOne(command.getId()); SavingProduct product = this.savingProductRepository.findOne(command.getId());
if (product == null) { if (product == null) { throw new SavingProductNotFoundException(command.getId()); }
throw new SavingProductNotFoundException(command.getId()); product.update(command);
} this.savingProductRepository.save(product);
product.update(command); return new EntityIdentifier(Long.valueOf(product.getId()));
this.savingProductRepository.save(product); }
return new EntityIdentifier(Long.valueOf(product.getId()));
}
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteSavingProduct(Long productId) { 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()));
}
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()));
}
} }
@@ -5,27 +5,31 @@ 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;
}
} }
@@ -259,15 +259,15 @@ 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();
} }
} }
@@ -67,9 +67,9 @@ public class DepositAccountData {
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,
@@ -126,9 +126,9 @@ public class DepositAccountData {
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,
@@ -178,9 +178,9 @@ public class DepositAccountData {
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,
@@ -230,9 +230,9 @@ public class DepositAccountData {
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;
@@ -292,9 +292,9 @@ public class DepositAccountData {
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,
@@ -347,9 +347,9 @@ public class DepositAccountData {
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){ private BigDecimal determineAvailableInterestForWithdrawal(final DepositAccountData account) {
if (account.getStatus().getId() == 300) { BigDecimal availableInterestForWithdrawal = BigDecimal.ZERO;
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()); if (this.status != null) {
}else { if (account.getStatus().getId() == 300) {
return BigDecimal.ZERO; BigDecimal interestGettingForPeriod = BigDecimal.valueOf(account.getActualInterestAccrued().doubleValue()
} / new Double(account.getTenureInMonths()));
}else return BigDecimal.ZERO; LocalDate interestWithdrawingDate = new LocalDate().isBefore(getMaturedOn()) ? new LocalDate() : getMaturedOn().plusDays(1);
Integer noOfMonthsforInterestCal = Months.monthsBetween(account.getActualCommencementDate(), interestWithdrawingDate)
.getMonths();
Integer noOfPeriods = noOfMonthsforInterestCal / account.getInterestCompoundedEvery();
return availableInterestForWithdrawal; availableInterestForWithdrawal = BigDecimal.valueOf(interestGettingForPeriod.multiply(new BigDecimal(noOfPeriods))
} .doubleValue() - account.getInterestPaid().doubleValue());
} else {
return BigDecimal.ZERO;
}
} else
return BigDecimal.ZERO;
private BigDecimal determineAvalableWithdrawalAmount(final DepositAccountData account) { return availableInterestForWithdrawal;
}
BigDecimal avalablePreclosureWithdrawalAmount = BigDecimal.ZERO; private BigDecimal determineAvalableWithdrawalAmount(final DepositAccountData account) {
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())){ BigDecimal avalablePreclosureWithdrawalAmount = BigDecimal.ZERO;
// Integer days = Days.daysBetween(account.getLastInterestPostedDate(), new LocalDate()).getDays(); if (this.status != null) {
// avalablePreclosureWithdrawalAmount=account.getAvailableInterest().add(account.getDeposit()).add(determineRemainInerestAmount(account.getDeposit(), account.getPreClosureInterestRate(), days)); if (account.getStatus().getId() == 300) {
// } // if(new LocalDate().isBefore(account.getMaturedOn()) || new
}else{ // LocalDate().isEqual(account.getMaturedOn())){
avalablePreclosureWithdrawalAmount=account.getDeposit(); Integer days = Days.daysBetween(account.getLastInterestPostedDate(), new LocalDate()).getDays();
} avalablePreclosureWithdrawalAmount = account.getAvailableInterest().add(account.getDeposit())
} .add(determineRemainInerestAmount(account.getDeposit(), account.getPreClosureInterestRate(), days));
return avalablePreclosureWithdrawalAmount;
}
private BigDecimal determineRemainInerestAmount(final BigDecimal depsoitAmount, final BigDecimal interstRateApplicable, final Integer 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;
}
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); private BigDecimal determineRemainInerestAmount(final BigDecimal depsoitAmount, final BigDecimal interstRateApplicable,
Integer daysInYear = 365; final Integer days) {
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());
} 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());
}
} }
@@ -10,51 +10,50 @@ import org.mifosplatform.infrastructure.core.data.EnumOptionData;
*/ */
public class DepositAccountTransactionData { public class DepositAccountTransactionData {
private final Long transactionId; private final Long transactionId;
private final EnumOptionData transactionType; private final EnumOptionData transactionType;
private final LocalDate transactionDate; private final LocalDate transactionDate;
private final BigDecimal transactionAmount; private final BigDecimal transactionAmount;
private final Long accountId; private final Long accountId;
private final BigDecimal interestAmount; private final BigDecimal interestAmount;
private final BigDecimal total; private final BigDecimal total;
public DepositAccountTransactionData( public DepositAccountTransactionData(final Long transactionId, final Long accountId, final EnumOptionData transactionType,
final Long transactionId, final Long accountId, final EnumOptionData transactionType, final LocalDate transactionDate, final BigDecimal transactionAmount, final BigDecimal interstAmount, final BigDecimal total) {
final LocalDate transactionDate, final BigDecimal transactionAmount, final BigDecimal interstAmount, final BigDecimal total ) { this.transactionId = transactionId;
this.transactionId = transactionId; this.accountId = accountId;
this.accountId = accountId; this.transactionType = transactionType;
this.transactionType = transactionType; this.transactionDate = transactionDate;
this.transactionDate = transactionDate; this.transactionAmount = transactionAmount;
this.transactionAmount = transactionAmount; this.interestAmount = interstAmount;
this.interestAmount = interstAmount; this.total = total;
this.total = total; }
}
public Long getAccountId() { public Long getAccountId() {
return accountId; return accountId;
} }
public Long getTransactionId() { public Long getTransactionId() {
return transactionId; return transactionId;
} }
public EnumOptionData getTransactionType() { public EnumOptionData getTransactionType() {
return transactionType; return transactionType;
} }
public LocalDate getTransactionDate() { public LocalDate getTransactionDate() {
return transactionDate; return transactionDate;
} }
public BigDecimal getTransactionAmount() { public BigDecimal getTransactionAmount() {
return transactionAmount; return transactionAmount;
} }
public BigDecimal getInterestAmount() { public BigDecimal getInterestAmount() {
return interestAmount; return interestAmount;
} }
public BigDecimal getTotal() { public BigDecimal getTotal() {
return total; return total;
} }
} }
@@ -2,14 +2,14 @@ package org.mifosplatform.portfolio.savingsdepositaccount.data;
public class DepositAccountsForLookup { public class DepositAccountsForLookup {
private final Long id; private final Long id;
public DepositAccountsForLookup(final Long id) { public DepositAccountsForLookup(final Long id) {
this.id = id; this.id = id;
} }
public Long getId() { public Long getId() {
return id; return id;
} }
} }
@@ -2,59 +2,59 @@ package org.mifosplatform.portfolio.savingsdepositaccount.data;
public class DepositPermissionData { public class DepositPermissionData {
private final boolean rejectAllowed; private final boolean rejectAllowed;
private final boolean withdrawnByApplicantAllowed; private final boolean withdrawnByApplicantAllowed;
private final boolean undoApprovalAllowed; private final boolean undoApprovalAllowed;
private final boolean pendingApproval; private final boolean pendingApproval;
private final boolean isInterestWithdrawalAllowed; private final boolean isInterestWithdrawalAllowed;
private final boolean renewelAllowed; private final boolean renewelAllowed;
private final boolean isMaturedDepositAccount; private final boolean isMaturedDepositAccount;
private final boolean anyActionOnAccountAllowed; private final boolean anyActionOnAccountAllowed;
public DepositPermissionData(final boolean rejectAllowed, final boolean withdrawnByApplicantAllowed, final boolean undoApprovalAllowed,
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 DepositPermissionData(final boolean rejectAllowed,final boolean withdrawnByApplicantAllowed,final boolean undoApprovalAllowed, public boolean isRejectAllowed() {
final boolean pendingApproval,final boolean interestWithdrawalAllowed, final boolean renewelAllowed, final boolean isMaturedDepositAccount) { return rejectAllowed;
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 isRejectAllowed() { public boolean isWithdrawnByApplicantAllowed() {
return rejectAllowed; return withdrawnByApplicantAllowed;
} }
public boolean isWithdrawnByApplicantAllowed() { public boolean isUndoApprovalAllowed() {
return withdrawnByApplicantAllowed; return undoApprovalAllowed;
} }
public boolean isUndoApprovalAllowed() { public boolean isPendingApproval() {
return undoApprovalAllowed; return pendingApproval;
} }
public boolean isPendingApproval() { public boolean isAnyActionOnAccountAllowed() {
return pendingApproval; return anyActionOnAccountAllowed;
} }
public boolean isAnyActionOnAccountAllowed() { public boolean isInterestWithdrawalAllowed() {
return anyActionOnAccountAllowed; return isInterestWithdrawalAllowed;
} }
public boolean isInterestWithdrawalAllowed() { public boolean isRenewelAllowed() {
return isInterestWithdrawalAllowed; return renewelAllowed;
} }
public boolean isRenewelAllowed() { public boolean isMaturedDepositAccount() {
return renewelAllowed; return isMaturedDepositAccount;
} }
public boolean isMaturedDepositAccount() {
return isMaturedDepositAccount;
}
} }
@@ -2,6 +2,5 @@ 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> {
} }
@@ -2,93 +2,93 @@ 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() { public boolean isSubmittedAndPendingApproval() {
return this.value.equals(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue()); return this.value.equals(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue());
} }
/*public boolean isApproved() { /*
return this.value.equals(DepositAccountStatus.APPROVED.getValue()); * public boolean isApproved() { return
}*/ * this.value.equals(DepositAccountStatus.APPROVED.getValue()); }
*/
public boolean isActive() { public boolean isActive() {
return this.value.equals(DepositAccountStatus.ACTIVE.getValue()); return this.value.equals(DepositAccountStatus.ACTIVE.getValue());
} }
public boolean isClosed() { public boolean isClosed() {
return this.value.equals(DepositAccountStatus.CLOSED.getValue()); return this.value.equals(DepositAccountStatus.CLOSED.getValue());
} }
public boolean isWithdrawnByClient() { public boolean isWithdrawnByClient() {
return this.value.equals(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue()); return this.value.equals(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue());
} }
public boolean isRejected() { public boolean isRejected() {
return this.value.equals(DepositAccountStatus.REJECTED.getValue()); return this.value.equals(DepositAccountStatus.REJECTED.getValue());
} }
public boolean isPreClosed(){ public boolean isPreClosed() {
return this.value.equals(DepositAccountStatus.PRECLOSED.getValue()); return this.value.equals(DepositAccountStatus.PRECLOSED.getValue());
} }
public static DepositAccountStatus fromInt(final Integer statusValue) { public static DepositAccountStatus fromInt(final Integer statusValue) {
DepositAccountStatus enumeration = DepositAccountStatus.INVALID; DepositAccountStatus enumeration = DepositAccountStatus.INVALID;
switch (statusValue) { switch (statusValue) {
case 100: case 100:
enumeration = DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL; enumeration = DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL;
break; break;
/*case 200: /*
enumeration = DepositAccountStatus.APPROVED; * case 200: enumeration = DepositAccountStatus.APPROVED; break;
break;*/ */
case 300: case 300:
enumeration = DepositAccountStatus.ACTIVE; enumeration = DepositAccountStatus.ACTIVE;
break; break;
case 400: case 400:
enumeration = DepositAccountStatus.WITHDRAWN_BY_CLIENT; enumeration = DepositAccountStatus.WITHDRAWN_BY_CLIENT;
break; break;
case 500: case 500:
enumeration = DepositAccountStatus.REJECTED; enumeration = DepositAccountStatus.REJECTED;
break; break;
case 600: case 600:
enumeration = DepositAccountStatus.CLOSED; enumeration = DepositAccountStatus.CLOSED;
break; break;
case 700: case 700:
enumeration = DepositAccountStatus.MATURED; enumeration = DepositAccountStatus.MATURED;
break; break;
case 800: case 800:
enumeration = DepositAccountStatus.PRECLOSED; enumeration = DepositAccountStatus.PRECLOSED;
break; break;
} }
return enumeration; 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() { public DepositAccountTransactionType getTypeOf() {
return typeOf; return typeOf;
} }
public Money getAmount(MonetaryCurrency currency) { public Money getAmount(MonetaryCurrency currency) {
return Money.of(currency, this.amount); 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) { 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()); return new DepositAccountTransaction(DepositAccountTransactionType.WITHDRAW, amount == null ? new BigDecimal(0)
} : amount.getAmount(), paymentDate, interest == null ? new BigDecimal(0) : interest.getAmount());
}
public static DepositAccountTransaction postInterest(Money depositAmount, LocalDate paymentDate, Money interest) { public static DepositAccountTransaction postInterest(Money depositAmount, LocalDate paymentDate, Money interest) {
return new DepositAccountTransaction(DepositAccountTransactionType.INTEREST_POSTING, depositAmount == null ? new BigDecimal(0) : depositAmount.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 void updateAccount(DepositAccount depositAccount) { public void updateAccount(DepositAccount depositAccount) {
this.depositAccount=depositAccount; this.depositAccount = depositAccount;
} }
} }
@@ -2,59 +2,56 @@ 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){ public static DepositAccountTransactionType fromInt(final Integer transactionType) {
if (transactionType == null) { if (transactionType == null) { return DepositAccountTransactionType.INVALID; }
return DepositAccountTransactionType.INVALID;
}
DepositAccountTransactionType depositTransactionType=null; DepositAccountTransactionType depositTransactionType = null;
switch (transactionType) { switch (transactionType) {
case 1: case 1:
depositTransactionType=DepositAccountTransactionType.DEPOSIT; depositTransactionType = DepositAccountTransactionType.DEPOSIT;
break; break;
case 2: case 2:
depositTransactionType=DepositAccountTransactionType.WITHDRAW; depositTransactionType = DepositAccountTransactionType.WITHDRAW;
break; break;
case 3: case 3:
depositTransactionType=DepositAccountTransactionType.REVERSAL; depositTransactionType = DepositAccountTransactionType.REVERSAL;
break; break;
case 4: case 4:
depositTransactionType=DepositAccountTransactionType.INTEREST_POSTING; depositTransactionType = DepositAccountTransactionType.INTEREST_POSTING;
break; break;
default : default:
depositTransactionType=DepositAccountTransactionType.INVALID; depositTransactionType = DepositAccountTransactionType.INVALID;
break; break;
} }
return depositTransactionType; 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; private final List<DepositAccountStatus> allowedDepositStatuses;
public DepositLifecycleStateMachineImpl(List<DepositAccountStatus> allowedDepositStatuses) { public DepositLifecycleStateMachineImpl(List<DepositAccountStatus> allowedDepositStatuses) {
this.allowedDepositStatuses=allowedDepositStatuses; this.allowedDepositStatuses = allowedDepositStatuses;
} }
@Override @Override
public DepositAccountStatus transition(DepositAccountEvent depositEvent, DepositAccountStatus from) { public DepositAccountStatus transition(DepositAccountEvent depositEvent, DepositAccountStatus from) {
DepositAccountStatus newState = null; DepositAccountStatus newState = null;
switch (depositEvent) { switch (depositEvent) {
case DEPOSIT_CREATED: case DEPOSIT_CREATED:
if (from == null) { if (from == null) {
newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses); newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses);
} }
break; break;
case DEPOSIT_REJECTED: case DEPOSIT_REJECTED:
if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) { if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) {
newState = stateOf(DepositAccountStatus.REJECTED, allowedDepositStatuses); newState = stateOf(DepositAccountStatus.REJECTED, allowedDepositStatuses);
} } else {
else{ final String errorMessage = "The DepositApplication can not be rejected from " + from.getCode();
final String errorMessage = "The DepositApplication can not be rejected from "+from.getCode() ; throw new InvalidDepositStateTransitionException("rejection", "failed", errorMessage, from);
throw new InvalidDepositStateTransitionException("rejection", "failed", errorMessage,from); }
} break;
break; case DEPOSIT_APPROVED:
case DEPOSIT_APPROVED: if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) {
if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) { newState = stateOf(DepositAccountStatus.ACTIVE, allowedDepositStatuses);
newState = stateOf(DepositAccountStatus.ACTIVE, allowedDepositStatuses); } else {
} final String errorMessage = "The DepositApplication can not be approved from " + from.getCode();
else{ throw new InvalidDepositStateTransitionException("approve", "failed", errorMessage, from);
final String errorMessage = "The DepositApplication can not be approved from "+from.getCode() ; }
throw new InvalidDepositStateTransitionException("approve", "failed", errorMessage,from); break;
} case DEPOSIT_WITHDRAWN:
break; if (this.anyOfAllowedWhenComingFrom(from, DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, DepositAccountStatus.ACTIVE)) {
case DEPOSIT_WITHDRAWN: newState = stateOf(DepositAccountStatus.WITHDRAWN_BY_CLIENT, allowedDepositStatuses);
if (this.anyOfAllowedWhenComingFrom(from, DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, DepositAccountStatus.ACTIVE)) { } else {
newState = stateOf(DepositAccountStatus.WITHDRAWN_BY_CLIENT, allowedDepositStatuses); final String errorMessage = "The DepositApplication can not be withdrawn from " + from.getCode();
} throw new InvalidDepositStateTransitionException("withdrawbyclient", "failed", errorMessage, from);
else{ }
final String errorMessage = "The DepositApplication can not be withdrawn from "+from.getCode() ; break;
throw new InvalidDepositStateTransitionException("withdrawbyclient", "failed", errorMessage,from); case DEPOSIT_APPROVAL_UNDO:
} if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
break; newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses);
case DEPOSIT_APPROVAL_UNDO: } else {
if (from.hasStateOf(DepositAccountStatus.ACTIVE)) { final String errorMessage = "The DepositApplication can not be unapproved from " + from.getCode();
newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses); throw new InvalidDepositStateTransitionException("unapprove", "failed", errorMessage, from);
} }
else{ break;
final String errorMessage = "The DepositApplication can not be unapproved from "+from.getCode() ; case DEPOSIT_MATURED:
throw new InvalidDepositStateTransitionException("unapprove", "failed", errorMessage,from); if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
} newState = stateOf(DepositAccountStatus.MATURED, allowedDepositStatuses);
break; } else {
case DEPOSIT_MATURED: final String errorMessage = "The DepositApplication can not be matured from " + from.getCode();
if (from.hasStateOf(DepositAccountStatus.ACTIVE) ){ throw new InvalidDepositStateTransitionException("mature", "failed", errorMessage, from);
newState = stateOf(DepositAccountStatus.MATURED, allowedDepositStatuses); }
} break;
else{ case DEPOSIT_CLOSED:
final String errorMessage = "The DepositApplication can not be matured from "+from.getCode() ; if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
throw new InvalidDepositStateTransitionException("mature", "failed", errorMessage,from); newState = stateOf(DepositAccountStatus.CLOSED, allowedDepositStatuses);
} } else {
break; final String errorMessage = "The DepositApplication can not be closed from " + from.getCode();
case DEPOSIT_CLOSED: throw new InvalidDepositStateTransitionException("closed", "failed", errorMessage, from);
if (from.hasStateOf(DepositAccountStatus.ACTIVE) ){ }
newState = stateOf(DepositAccountStatus.CLOSED, allowedDepositStatuses); break;
} case DEPOSIT_PRECLOSED:
else{ if (from.hasStateOf(DepositAccountStatus.ACTIVE)) {
final String errorMessage = "The DepositApplication can not be closed from "+from.getCode() ; newState = stateOf(DepositAccountStatus.PRECLOSED, allowedDepositStatuses);
throw new InvalidDepositStateTransitionException("closed", "failed", errorMessage,from); } else {
} final String errorMessage = "The DepositApplication can not be matured from " + from.getCode();
break; throw new InvalidDepositStateTransitionException("preclosure", "failed", errorMessage, from);
case DEPOSIT_PRECLOSED: }
if (from.hasStateOf(DepositAccountStatus.ACTIVE) ){ break;
newState = stateOf(DepositAccountStatus.PRECLOSED, allowedDepositStatuses); default:
} break;
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; return newState;
} }
private DepositAccountStatus stateOf(DepositAccountStatus state, List<DepositAccountStatus> allowedLoanStatuses) { private DepositAccountStatus stateOf(DepositAccountStatus state, List<DepositAccountStatus> allowedLoanStatuses) {
DepositAccountStatus match = null; DepositAccountStatus match = null;
for (DepositAccountStatus depositStatus : allowedLoanStatuses) { for (DepositAccountStatus depositStatus : allowedLoanStatuses) {
if (depositStatus.hasStateOf(state)) { if (depositStatus.hasStateOf(state)) {
match = depositStatus; match = depositStatus;
break; break;
} }
} }
return match; return match;
} }
private boolean anyOfAllowedWhenComingFrom(final DepositAccountStatus state, final DepositAccountStatus... allowedStates) { private boolean anyOfAllowedWhenComingFrom(final DepositAccountStatus state, final DepositAccountStatus... allowedStates) {
boolean allowed = false; boolean allowed = false;
for (DepositAccountStatus allowedState : allowedStates) { for (DepositAccountStatus allowedState : allowedStates) {
if (state.hasStateOf(allowedState)) { if (state.hasStateOf(allowedState)) {
allowed = true; allowed = true;
break; break;
} }
} }
return allowed; 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
// selected type.
// - the special case of 'simple interest' or 'no compounding' would use
// simple formula rather than 'future value' function.
// FIXME - assuming only monthly compounding period for now // FIXME - assuming only monthly compounding period for now
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer monthsInYear = 12; Integer monthsInYear = 12;
BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc); BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc); BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc);
BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()), mc); BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()),
mc);
Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery; Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery;
return fv(ratePerCompoundingPeriod, numberOfPeriods, deposit); return fv(ratePerCompoundingPeriod, numberOfPeriods, deposit);
} }
private static Money fv(final BigDecimal ratePerCompoundingPeriod, final Integer numberOfPeriods, final Money presentValue) { private static Money fv(final BigDecimal ratePerCompoundingPeriod, final Integer numberOfPeriods, final Money presentValue) {
double pmtPerPeriod = Double.valueOf("0.0"); double pmtPerPeriod = Double.valueOf("0.0");
double pv = presentValue.negated().getAmount().doubleValue(); double pv = presentValue.negated().getAmount().doubleValue();
double futureValue = fv(ratePerCompoundingPeriod.doubleValue(), numberOfPeriods.doubleValue(), pmtPerPeriod, pv, false); double futureValue = fv(ratePerCompoundingPeriod.doubleValue(), numberOfPeriods.doubleValue(), pmtPerPeriod, pv, false);
return Money.of(presentValue.getCurrency(), BigDecimal.valueOf(futureValue)); return Money.of(presentValue.getCurrency(), BigDecimal.valueOf(futureValue));
} }
/** /**
* Future value of an amount given the number of payments, rate, amount of * Future value of an amount given the number of payments, rate, amount of
* individual payment, present value and boolean value indicating whether * individual payment, present value and boolean value indicating whether
* payments are due at the beginning of period (false => payments are due at * payments are due at the beginning of period (false => payments are due at
* end of period) * end of period)
*/ */
private static double fv(double ratePeriodCompoundingPeriod, double numberOfCompoundingPeriods, double pmtPerPeriod, double presentValue, boolean type) { private static double fv(double ratePeriodCompoundingPeriod, double numberOfCompoundingPeriods, double pmtPerPeriod,
double retval = 0; double presentValue, boolean type) {
if (ratePeriodCompoundingPeriod == 0) { double retval = 0;
retval = -1 * (presentValue + (numberOfCompoundingPeriods * pmtPerPeriod)); if (ratePeriodCompoundingPeriod == 0) {
} else { retval = -1 * (presentValue + (numberOfCompoundingPeriods * pmtPerPeriod));
double r1 = ratePeriodCompoundingPeriod + 1; } else {
retval = ((1 - Math.pow(r1, numberOfCompoundingPeriods)) * (type ? r1 : 1) * pmtPerPeriod) / ratePeriodCompoundingPeriod - presentValue double r1 = ratePeriodCompoundingPeriod + 1;
* Math.pow(r1, numberOfCompoundingPeriods); retval = ((1 - Math.pow(r1, numberOfCompoundingPeriods)) * (type ? r1 : 1) * pmtPerPeriod) / ratePeriodCompoundingPeriod
} - presentValue * Math.pow(r1, numberOfCompoundingPeriods);
return retval; }
} return retval;
}
public Money calculateInterestOnMaturityForSimpleInterest(Money deposit, public Money calculateInterestOnMaturityForSimpleInterest(Money deposit, Integer tenureInMonths, BigDecimal maturityInterestRate,
Integer tenureInMonths, BigDecimal maturityInterestRate, Integer interestCompoundedEvery, PeriodFrequencyType interestCompoundedFrequencyPeriodType) {
Integer interestCompoundedEvery,
PeriodFrequencyType interestCompoundedFrequencyPeriodType) {
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer monthsInYear = 12; Integer monthsInYear = 12;
BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc); BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc); BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc);
BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()), mc); BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()),
Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery; mc);
Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery;
BigDecimal interest = ratePerCompoundingPeriod.multiply(deposit.getAmount()).multiply(BigDecimal.valueOf(new Double(numberOfPeriods))); BigDecimal interest = ratePerCompoundingPeriod.multiply(deposit.getAmount()).multiply(
BigDecimal totalAmount =deposit.getAmount().add(interest); BigDecimal.valueOf(new Double(numberOfPeriods)));
BigDecimal totalAmount = deposit.getAmount().add(interest);
return Money.of(deposit.getCurrency(), totalAmount); return Money.of(deposit.getCurrency(), totalAmount);
} }
public Money calculateRemainInterest(Money deposit, Integer days, BigDecimal interestRate){ public Money calculateRemainInterest(Money deposit, Integer days, BigDecimal interestRate) {
MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
Integer daysInYear = 365; Integer daysInYear = 365;
BigDecimal interestRateAsFraction = interestRate.divide(BigDecimal.valueOf(100), mc); BigDecimal interestRateAsFraction = interestRate.divide(BigDecimal.valueOf(100), mc);
BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc); BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc);
BigDecimal interest = BigDecimal.valueOf(deposit.getAmount().doubleValue()*days.doubleValue()*interestRateForOneDay.doubleValue()); BigDecimal interest = BigDecimal.valueOf(deposit.getAmount().doubleValue() * days.doubleValue()
* interestRateForOneDay.doubleValue());
return Money.of(deposit.getCurrency(), interest); 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()); }
DepositProduct product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) { boolean isInterestWithdrawable = command.isInterestWithdrawable();
throw new DepositProductNotFoundException(command.getProductId());
} // details inherited from product setting (unless allowed to be
// overridden through account creation api
boolean isInterestWithdrawable = command.isInterestWithdrawable(); Money deposit = Money.of(product.getCurrency(), command.getDepositAmount());
// details inherited from product setting (unless allowed to be overridden through account creation api Integer tenureInMonths = product.getTenureInMonths();
Money deposit = Money.of(product.getCurrency(), command.getDepositAmount()); if (command.getTenureInMonths() != null) {
tenureInMonths = command.getTenureInMonths();
Integer tenureInMonths = product.getTenureInMonths(); }
if (command.getTenureInMonths() != null) {
tenureInMonths = command.getTenureInMonths(); BigDecimal maturityInterestRate = product.getMaturityDefaultInterestRate();
} if (command.getMaturityInterestRate() != null) {
maturityInterestRate = command.getMaturityInterestRate();
BigDecimal maturityInterestRate = product.getMaturityDefaultInterestRate(); }
if (command.getMaturityInterestRate() != null) {
maturityInterestRate = command.getMaturityInterestRate(); BigDecimal preClosureInterestRate = product.getPreClosureInterestRate();
} if (command.getPreClosureInterestRate() != null) {
preClosureInterestRate = command.getPreClosureInterestRate();
BigDecimal preClosureInterestRate = product.getPreClosureInterestRate(); }
if(command.getPreClosureInterestRate()!=null){
preClosureInterestRate = command.getPreClosureInterestRate(); if (product.getMaturityMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException(
} preClosureInterestRate, product.getMaturityMinInterestRate()); }
if(product.getMaturityMinInterestRate().compareTo(preClosureInterestRate)==-1){ Integer compoundingInterestEvery = product.getInterestCompoundedEvery();
throw new DepositAccounDataValidationtException(preClosureInterestRate, product.getMaturityMinInterestRate()); if (command.getInterestCompoundedEvery() != null) {
} compoundingInterestEvery = command.getInterestCompoundedEvery();
}
Integer compoundingInterestEvery = product.getInterestCompoundedEvery();
if (command.getInterestCompoundedEvery() != null) { PeriodFrequencyType compoundingInterestFrequency = product.getInterestCompoundedEveryPeriodType();
compoundingInterestEvery = command.getInterestCompoundedEvery(); if (command.getInterestCompoundedEveryPeriodType() != null) {
} compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
PeriodFrequencyType compoundingInterestFrequency = product.getInterestCompoundedEveryPeriodType();
if (command.getInterestCompoundedEveryPeriodType() != null) { boolean renewalAllowed = product.isRenewalAllowed();
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType()); if (command.isRenewalAllowedChanged()) {
} renewalAllowed = command.isRenewalAllowed();
}
boolean renewalAllowed = product.isRenewalAllowed();
if (command.isRenewalAllowedChanged()) { boolean preClosureAllowed = product.isPreClosureAllowed();
renewalAllowed = command.isRenewalAllowed(); if (command.isPreClosureAllowedChanged()) {
} preClosureAllowed = command.isPreClosureAllowed();
}
boolean preClosureAllowed = product.isPreClosureAllowed();
if (command.isPreClosureAllowedChanged()) { boolean interestCompoundingAllowed = product.isInterestCompoundingAllowed();
preClosureAllowed = command.isPreClosureAllowed(); if (command.isInterestCompoundingAllowedChanged()) {
} interestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
boolean interestCompoundingAllowed= product.isInterestCompoundingAllowed();
if(command.isInterestCompoundingAllowedChanged()){ boolean isLockinPeriodAllowed = product.isLockinPeriodAllowed();
interestCompoundingAllowed = command.isInterestCompoundingAllowed(); if (command.isLockinPeriodChanged()) {
} isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
boolean isLockinPeriodAllowed = product.isLockinPeriodAllowed();
if(command.isLockinPeriodChanged()){ Integer lockinPeriod = product.getLockinPeriod();
isLockinPeriodAllowed = command.isLockinPeriodAllowed(); if (command.getLockinPeriod() != null) {
} lockinPeriod = command.getLockinPeriod();
}
Integer lockinPeriod = product.getLockinPeriod();
if(command.getLockinPeriod() != null){ PeriodFrequencyType lockinPeriodType = product.getLockinPeriodType();
lockinPeriod = command.getLockinPeriod(); if (command.getLockinPeriodType() != null) {
} lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
}
PeriodFrequencyType lockinPeriodType = product.getLockinPeriodType(); // end of details allowed to be overriden from product
if(command.getLockinPeriodType() != null){
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); DepositAccount account = new DepositAccount().openNew(client, product, command.getExternalId(), deposit, maturityInterestRate,
} preClosureInterestRate, tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency,
// end of details allowed to be overriden from product command.getCommencementDate(), renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator,
defaultDepositLifecycleStateMachine(), isInterestWithdrawable, interestCompoundingAllowed, isLockinPeriodAllowed,
DepositAccount account =new DepositAccount().openNew(client, product, command.getExternalId(), lockinPeriod, lockinPeriodType);
deposit,
maturityInterestRate, preClosureInterestRate, return account;
tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency, }
command.getCommencementDate(),
renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator, private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() {
defaultDepositLifecycleStateMachine(),isInterestWithdrawable,interestCompoundingAllowed, List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values());
isLockinPeriodAllowed,lockinPeriod,lockinPeriodType); return new DepositLifecycleStateMachineImpl(allowedDepositStatuses);
}
return account;
} public DepositAccount assembleFrom(DepositAccount account, DepositAccountCommand command) {
private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() { Client client = account.client();
List<DepositAccountStatus> allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values());
return new DepositLifecycleStateMachineImpl(allowedDepositStatuses); DepositProduct product = account.product();
} if (command.getProductId() != null) {
product = this.depositProductRepository.findOne(command.getProductId());
public DepositAccount assembleFrom(DepositAccount account, DepositAccountCommand command) { if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(command.getProductId()); }
}
Client client = account.client();
Money deposit = account.getDeposit();
DepositProduct product = account.product(); if (command.getDepositAmount() != null) {
if(command.getProductId() != null){ deposit = Money.of(account.getDeposit().getCurrency(), command.getDepositAmount());
product = this.depositProductRepository.findOne(command.getProductId()); }
if (product == null || product.isDeleted()) {
throw new DepositProductNotFoundException(command.getProductId()); Integer tenureInMonths = account.getTenureInMonths();
} if (command.getTenureInMonths() != null) {
} tenureInMonths = command.getTenureInMonths();
}
Money deposit = account.getDeposit();
if(command.getDepositAmount() != null){ BigDecimal maturityInterestRate = account.getInterestRate();
deposit = Money.of(account.getDeposit().getCurrency(), command.getDepositAmount()); if (command.getMaturityInterestRate() != null) {
} maturityInterestRate = command.getMaturityInterestRate();
}
Integer tenureInMonths = account.getTenureInMonths();
if(command.getTenureInMonths() != null){ BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
tenureInMonths =command.getTenureInMonths(); if (command.getPreClosureInterestRate() != null) {
} preClosureInterestRate = command.getPreClosureInterestRate();
}
BigDecimal maturityInterestRate = account.getInterestRate();
if(command.getMaturityInterestRate() != null){ if (product.getMaturityMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException(
maturityInterestRate = command.getMaturityInterestRate(); preClosureInterestRate, product.getMaturityMinInterestRate()); }
}
Integer compoundingInterestEvery = account.getInterestCompoundedEvery();
BigDecimal preClosureInterestRate = account.getPreClosureInterestRate(); if (command.getInterestCompoundedEvery() != null) {
if(command.getPreClosureInterestRate() != null){ compoundingInterestEvery = command.getInterestCompoundedEvery();
preClosureInterestRate = command.getPreClosureInterestRate(); }
}
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType();
if (command.getInterestCompoundedEveryPeriodType() != null) {
if(product.getMaturityMinInterestRate().compareTo(preClosureInterestRate)==-1){ compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
throw new DepositAccounDataValidationtException(preClosureInterestRate, product.getMaturityMinInterestRate()); }
}
boolean renewalAllowed = account.isRenewalAllowed();
Integer compoundingInterestEvery = account.getInterestCompoundedEvery(); if (command.isRenewalAllowedChanged()) {
if(command.getInterestCompoundedEvery() != null){ renewalAllowed = command.isRenewalAllowed();
compoundingInterestEvery = command.getInterestCompoundedEvery(); }
}
boolean preClosureAllowed = account.isPreClosureAllowed();
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType(); if (command.isPreClosureAllowedChanged()) {
if(command.getInterestCompoundedEveryPeriodType() !=null){ preClosureAllowed = command.isPreClosureAllowed();
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType()); }
}
boolean isInterestWithdrawable = account.isInterestWithdrawable();
boolean renewalAllowed = account.isRenewalAllowed(); if (command.isInterestWithdrawableChanged()) {
if(command.isRenewalAllowedChanged()){ isInterestWithdrawable = command.isInterestWithdrawable();
renewalAllowed = command.isRenewalAllowed(); }
}
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed();
boolean preClosureAllowed = account.isPreClosureAllowed(); if (command.isInterestCompoundingAllowedChanged()) {
if(command.isPreClosureAllowedChanged()){ isInterestCompoundingAllowed = command.isInterestCompoundingAllowed();
preClosureAllowed = command.isPreClosureAllowed(); }
}
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
boolean isInterestWithdrawable = account.isInterestWithdrawable(); if (command.isLockinPeriodChanged()) {
if(command.isInterestWithdrawableChanged()){ isLockinPeriodAllowed = command.isLockinPeriodAllowed();
isInterestWithdrawable = command.isInterestWithdrawable(); }
}
Integer lockinPeriod = account.getLockinPeriod();
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed(); if (command.getLockinPeriod() != null) {
if(command.isInterestCompoundingAllowedChanged()){ lockinPeriod = command.getLockinPeriod();
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed(); }
}
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); if (command.getLockinPeriodType() != null) {
if(command.isLockinPeriodChanged()){ lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
isLockinPeriodAllowed = command.isLockinPeriodAllowed(); }
}
DepositAccount newAccount = new DepositAccount().openNew(client, product, null, deposit, maturityInterestRate,
Integer lockinPeriod = account.getLockinPeriod(); preClosureInterestRate, tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency, account.maturesOnDate()
if(command.getLockinPeriod() != null){ .plusDays(1), renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator,
lockinPeriod = command.getLockinPeriod(); defaultDepositLifecycleStateMachine(), isInterestWithdrawable, isInterestCompoundingAllowed, isLockinPeriodAllowed,
} lockinPeriod, lockinPeriodType);
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType(); newAccount.updateAccount(account);
if(command.getLockinPeriodType() != null){
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); return newAccount;
} }
DepositAccount newAccount =new DepositAccount().openNew(client, product, null, /*
deposit, * public void adjustTotalAmountForPreclosureInterest(DepositAccount
maturityInterestRate, preClosureInterestRate, * account,LocalDate eventDate) {
tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency, * account.adjustTotalAmountForPreclosureInterest
account.maturesOnDate().plusDays(1), * (account,this.fixedTermDepositInterestCalculator,eventDate); }
renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator, defaultDepositLifecycleStateMachine(), */
isInterestWithdrawable,isInterestCompoundingAllowed,isLockinPeriodAllowed,lockinPeriod,lockinPeriodType);
public void assembleUpdatedDepositAccount(DepositAccount account, DepositAccountCommand command) {
newAccount.updateAccount(account);
DepositProduct product = account.product();
return newAccount; if (command.getProductId() != null) {
} product = this.depositProductRepository.findOne(command.getProductId());
if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(command.getProductId()); }
/*public void adjustTotalAmountForPreclosureInterest(DepositAccount account,LocalDate eventDate) { }
account.adjustTotalAmountForPreclosureInterest(account,this.fixedTermDepositInterestCalculator,eventDate);
}*/ String externalId = account.getExternalId();
if (command.isExternalIdChanged()) {
public void assembleUpdatedDepositAccount(DepositAccount account,DepositAccountCommand command) { externalId = command.getExternalId();
}
DepositProduct product = account.product();
if(command.getProductId() != null){ LocalDate commencementDate = account.getProjectedCommencementDate();
product = this.depositProductRepository.findOne(command.getProductId()); if (command.isCommencementDateChanged()) {
if (product == null || product.isDeleted()) { commencementDate = new LocalDate(command.getCommencementDate());
throw new DepositProductNotFoundException(command.getProductId()); }
}
} Money deposit = account.getDeposit();
if (command.isDepositAmountChanged()) {
String externalId = account.getExternalId(); deposit = Money.of(product.getCurrency(), command.getDepositAmount());
if(command.isExternalIdChanged()){ }
externalId = command.getExternalId();
} Integer tenureInMonths = account.getTenureInMonths();
if (command.isTenureInMonthsChanged()) {
LocalDate commencementDate = account.getProjectedCommencementDate(); tenureInMonths = command.getTenureInMonths();
if(command.isCommencementDateChanged()){ }
commencementDate = new LocalDate(command.getCommencementDate());
} BigDecimal maturityInterestRate = account.getInterestRate();
if (command.isMaturityActualInterestRateChanged()) {
Money deposit = account.getDeposit(); maturityInterestRate = command.getMaturityInterestRate();
if(command.isDepositAmountChanged()){ }
deposit = Money.of(product.getCurrency(), command.getDepositAmount());
} BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
if (command.isPreClosureInterestRateChanged()) {
Integer tenureInMonths = account.getTenureInMonths(); preClosureInterestRate = command.getPreClosureInterestRate();
if(command.isTenureInMonthsChanged()){ }
tenureInMonths =command.getTenureInMonths();
} if (product.getMaturityMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException(
preClosureInterestRate, product.getMaturityMinInterestRate()); }
BigDecimal maturityInterestRate = account.getInterestRate();
if(command.isMaturityActualInterestRateChanged()){ Integer compoundingInterestEvery = account.getInterestCompoundedEvery();
maturityInterestRate = command.getMaturityInterestRate(); if (command.isCompoundingInterestEveryChanged()) {
} compoundingInterestEvery = command.getInterestCompoundedEvery();
}
BigDecimal preClosureInterestRate = account.getPreClosureInterestRate();
if(command.isPreClosureInterestRateChanged()){ PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType();
preClosureInterestRate = command.getPreClosureInterestRate(); if (command.getInterestCompoundedEveryPeriodType() != null) {
} compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType());
}
if(product.getMaturityMinInterestRate().compareTo(preClosureInterestRate)==-1){
throw new DepositAccounDataValidationtException(preClosureInterestRate, product.getMaturityMinInterestRate()); boolean renewalAllowed = account.isRenewalAllowed();
} if (command.isRenewalAllowedChanged()) {
renewalAllowed = command.isRenewalAllowed();
Integer compoundingInterestEvery = account.getInterestCompoundedEvery(); }
if(command.isCompoundingInterestEveryChanged()){
compoundingInterestEvery = command.getInterestCompoundedEvery(); boolean preClosureAllowed = account.isPreClosureAllowed();
} if (command.isPreClosureAllowedChanged()) {
preClosureAllowed = command.isPreClosureAllowed();
PeriodFrequencyType compoundingInterestFrequency = account.getInterestCompoundedFrequencyType(); }
if(command.getInterestCompoundedEveryPeriodType() !=null){
compoundingInterestFrequency = PeriodFrequencyType.fromInt(command.getInterestCompoundedEveryPeriodType()); boolean isInterestWithdrawable = account.isInterestWithdrawable();
} if (command.isInterestWithdrawableChanged()) {
isInterestWithdrawable = command.isInterestWithdrawable();
boolean renewalAllowed = account.isRenewalAllowed(); }
if(command.isRenewalAllowedChanged()){
renewalAllowed = command.isRenewalAllowed(); boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed();
} if (command.isInterestCompoundingAllowedChanged()) {
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed();
boolean preClosureAllowed = account.isPreClosureAllowed(); }
if(command.isPreClosureAllowedChanged()){
preClosureAllowed = command.isPreClosureAllowed(); boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed();
} if (command.isLockinPeriodChanged()) {
isLockinPeriodAllowed = command.isLockinPeriodAllowed();
boolean isInterestWithdrawable = account.isInterestWithdrawable(); }
if(command.isInterestWithdrawableChanged()){
isInterestWithdrawable = command.isInterestWithdrawable(); Integer lockinPeriod = account.getLockinPeriod();
} if (command.getLockinPeriod() != null) {
lockinPeriod = command.getLockinPeriod();
boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed(); }
if(command.isInterestCompoundingAllowedChanged()){
isInterestCompoundingAllowed = command.isInterestCompoundingAllowed(); PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType();
} if (command.getLockinPeriodType() != null) {
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType());
boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); }
if(command.isLockinPeriodChanged()){ account.update(product, externalId, commencementDate, deposit, tenureInMonths, maturityInterestRate, preClosureInterestRate,
isLockinPeriodAllowed = command.isLockinPeriodAllowed(); compoundingInterestEvery, compoundingInterestFrequency, renewalAllowed, preClosureAllowed, isInterestWithdrawable,
} isInterestCompoundingAllowed, this.fixedTermDepositInterestCalculator, isLockinPeriodAllowed, lockinPeriod,
lockinPeriodType);
Integer lockinPeriod = account.getLockinPeriod(); }
if(command.getLockinPeriod() != null){
lockinPeriod = command.getLockinPeriod(); public void updateApprovedDepositAccount(DepositAccount account, DepositAccountCommand command) {
}
boolean renewalAllowed = account.isRenewalAllowed();
PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType(); if (command.isRenewalAllowedChanged()) {
if(command.getLockinPeriodType() != null){ renewalAllowed = command.isRenewalAllowed();
lockinPeriodType = PeriodFrequencyType.fromInt(command.getLockinPeriodType()); }
}
account.update(product,externalId,commencementDate,deposit,tenureInMonths,maturityInterestRate,preClosureInterestRate,compoundingInterestEvery,compoundingInterestFrequency,renewalAllowed, boolean isInterestWithdrawable = account.isInterestWithdrawable();
preClosureAllowed,isInterestWithdrawable,isInterestCompoundingAllowed,this.fixedTermDepositInterestCalculator,isLockinPeriodAllowed,lockinPeriod,lockinPeriodType); if (command.isInterestWithdrawableChanged()) {
} isInterestWithdrawable = command.isInterestWithdrawable();
}
public void updateApprovedDepositAccount(DepositAccount account, DepositAccountCommand command) { account.update(renewalAllowed, isInterestWithdrawable);
boolean renewalAllowed = account.isRenewalAllowed(); }
if(command.isRenewalAllowedChanged()){
renewalAllowed = command.isRenewalAllowed(); public void postInterest(DepositAccount account) {
} account.postInterestForDepositAccount(account, this.fixedTermDepositInterestCalculator);
}
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;
}
} }
@@ -210,16 +210,17 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
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();
} }
} }
@@ -278,26 +290,26 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
} }
@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> { private static final class DepositAccountLookupMapper implements RowMapper<DepositAccountsForLookup> {
public String depositAccountLookupSchema(){ public String depositAccountLookupSchema() {
return " da.id as id from m_deposit_account da where da.status_enum=300 and da.is_deleted=0"; return " da.id as id from m_deposit_account da where da.status_enum=300 and da.is_deleted=0";
} }
@Override @Override
public DepositAccountsForLookup mapRow(ResultSet rs, int rowNum) throws SQLException { public DepositAccountsForLookup mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
return new DepositAccountsForLookup(id); return new DepositAccountsForLookup(id);
} }
} }
} }
@@ -5,30 +5,34 @@ import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountTr
public class DepositAccountTransactionEnumerations { public class DepositAccountTransactionEnumerations {
public static EnumOptionData depositType(final Integer statusId) { public static EnumOptionData depositType(final Integer statusId) {
return depositType(DepositAccountTransactionType.fromInt(statusId)); return depositType(DepositAccountTransactionType.fromInt(statusId));
} }
private static EnumOptionData depositType(DepositAccountTransactionType transactionType) { private static EnumOptionData depositType(DepositAccountTransactionType transactionType) {
EnumOptionData optionData=null; EnumOptionData optionData = null;
switch (transactionType) { switch (transactionType) {
case DEPOSIT: case DEPOSIT:
optionData=new EnumOptionData(DepositAccountTransactionType.DEPOSIT.getValue().longValue(), DepositAccountTransactionType.DEPOSIT.getCode(), "Deposit"); optionData = new EnumOptionData(DepositAccountTransactionType.DEPOSIT.getValue().longValue(),
break; DepositAccountTransactionType.DEPOSIT.getCode(), "Deposit");
break;
case WITHDRAW: case WITHDRAW:
optionData=new EnumOptionData(DepositAccountTransactionType.WITHDRAW.getValue().longValue(), DepositAccountTransactionType.WITHDRAW.getCode(), "Withdraw"); optionData = new EnumOptionData(DepositAccountTransactionType.WITHDRAW.getValue().longValue(),
break; DepositAccountTransactionType.WITHDRAW.getCode(), "Withdraw");
break;
case REVERSAL: case REVERSAL:
optionData=new EnumOptionData(DepositAccountTransactionType.REVERSAL.getValue().longValue(), DepositAccountTransactionType.REVERSAL.getCode(), "Revarsal"); optionData = new EnumOptionData(DepositAccountTransactionType.REVERSAL.getValue().longValue(),
break; DepositAccountTransactionType.REVERSAL.getCode(), "Revarsal");
default: break;
optionData=new EnumOptionData(DepositAccountTransactionType.INVALID.getValue().longValue(), DepositAccountTransactionType.INVALID.getCode(), "Invalid Transaction"); default:
break; optionData = new EnumOptionData(DepositAccountTransactionType.INVALID.getValue().longValue(),
} DepositAccountTransactionType.INVALID.getCode(), "Invalid Transaction");
return optionData; break;
} }
return optionData;
}
} }
@@ -54,5 +54,5 @@ public interface DepositAccountWritePlatformService {
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();
@@ -422,25 +423,22 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
} }
} }
@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));
}
} }
} }
@@ -10,23 +10,21 @@ import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositStateTra
public class DepositStateTransitionCommandValidator { public class DepositStateTransitionCommandValidator {
private final DepositStateTransitionCommand command; private final DepositStateTransitionCommand command;
public DepositStateTransitionCommandValidator(final DepositStateTransitionCommand command) { public DepositStateTransitionCommandValidator(final DepositStateTransitionCommand command) {
this.command=command; this.command = command;
} }
public void validate(){ public void validate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transition"); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transition");
baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero(); baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero();
baseDataValidator.reset().parameter("eventDate").value(command.getEventDate()).notNull(); baseDataValidator.reset().parameter("eventDate").value(command.getEventDate()).notNull();
baseDataValidator.reset().parameter("note").value(command.getNote()).notNull(); baseDataValidator.reset().parameter("note").value(command.getNote()).notNull();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); }
}
} }
@@ -10,34 +10,37 @@ import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositAccountC
public class RenewDepositAccountCommandValidator { public class RenewDepositAccountCommandValidator {
private final DepositAccountCommand command; private final DepositAccountCommand command;
public RenewDepositAccountCommandValidator(final DepositAccountCommand command) { public RenewDepositAccountCommandValidator(final DepositAccountCommand command) {
this.command=command; this.command = command;
} }
public void validateForCreate() { public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account");
baseDataValidator.reset().parameter("clientId").value(command.getClientId()).ignoreIfNull(); baseDataValidator.reset().parameter("clientId").value(command.getClientId()).ignoreIfNull();
baseDataValidator.reset().parameter("productId").value(command.getProductId()).ignoreIfNull(); baseDataValidator.reset().parameter("productId").value(command.getProductId()).ignoreIfNull();
baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100); baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100);
baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().zeroOrPositiveAmount();
baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull()
baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); .zeroOrPositiveAmount();
baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().integerGreaterThanZero(); 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("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull()
baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()).ignoreIfNull().inMinMaxRange(2, 2); .integerGreaterThanZero();
baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).ignoreIfNull(); baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType())
.ignoreIfNull().inMinMaxRange(2, 2);
baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).ignoreIfNull();
if (!dataValidationErrors.isEmpty()) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); "Validation errors exist.", dataValidationErrors); }
} }
}
} }