From 2c8efb4977edf111c4e2a0b2bec622bd78e6fa22 Mon Sep 17 00:00:00 2001 From: Keith Woodlock Date: Wed, 20 Mar 2013 00:35:56 +0000 Subject: [PATCH] MIFOSX-245: add basic shell for savings products and accounts. --- api-docs/apiLive.htm | 2786 +++++------------ ...hema-replace-with-basic-savings-schema.sql | 66 + .../service/CommandWrapperBuilder.java | 228 +- .../SynchronousCommandProcessingService.java | 24 +- .../ReadWriteNonCoreDataServiceImpl.java | 8 + .../domain/AccountNumberGeneratorFactory.java | 4 + .../portfolio/client/domain/Client.java | 28 +- .../ClientReadPlatformServiceImpl.java | 146 +- .../portfolio/group/domain/Group.java | 5 +- .../loanaccount/api/LoansApiResource.java | 2 - .../portfolio/loanaccount/domain/Loan.java | 6 +- .../loanschedule/domain/AprCalculator.java | 6 +- .../portfolio/note/api/NotesApiResource.java | 78 +- .../portfolio/note/domain/Note.java | 45 +- .../portfolio/note/domain/NoteRepository.java | 4 +- .../portfolio/note/domain/NoteType.java | 8 +- .../note/service/NoteEnumerations.java | 9 +- .../service/NoteReadPlatformServiceImpl.java | 19 +- ...WritePlatformServiceJpaRepositoryImpl.java | 210 +- .../api/SavingsAccountsApiResource.java | 168 + .../savings/api/SavingsApiConstants.java | 63 + .../api/SavingsProductsApiResource.java} | 136 +- .../savings/data/SavingsAccountData.java | 123 + .../data/SavingsAccountDataValidator.java | 244 ++ .../savings/data/SavingsProductData.java | 119 + .../data/SavingsProductDataValidator.java | 172 + .../savings/domain/SavingsAccount.java | 235 ++ .../domain/SavingsAccountAssembler.java | 132 + .../domain/SavingsAccountRepository.java} | 4 +- .../savings/domain/SavingsProduct.java | 215 ++ .../domain/SavingsProductAssembler.java | 51 + .../domain/SavingsProductRepository.java} | 4 +- ...nvalidSavingsProductSettingsException.java | 10 + .../SavingsAccountNotFoundException.java} | 8 +- .../SavingsProductNotFoundException.java} | 6 +- .../CreateSavingsAccountCommandHandler.java | 26 + .../CreateSavingsProductCommandHandler.java | 24 + .../DeleteSavingsAccountCommandHandler.java | 27 + .../DeleteSavingsProductCommandHandler.java} | 12 +- .../UpdateSavingsAccountCommandHandler.java | 27 + .../UpdateSavingsProductCommandHandler.java} | 12 +- .../SavingsAccountReadPlatformService.java | 19 + ...SavingsAccountReadPlatformServiceImpl.java | 289 ++ .../SavingsAccountWritePlatformService.java | 22 + ...WritePlatformServiceJpaRepositoryImpl.java | 253 ++ .../SavingsDropdownReadPlatformService.java | 12 + ...avingsDropdownReadPlatformServiceImpl.java | 34 + .../savings/service/SavingsEnumerations.java | 74 + .../SavingsProductReadPlatformService.java | 20 + ...SavingsProductReadPlatformServiceImpl.java | 132 + .../SavingsProductWritePlatformService.java} | 10 +- ...WritePlatformServiceJpaRepositoryImpl.java | 131 + .../api/SavingsAccountApiResource.java | 330 -- .../data/SavingAccountData.java | 511 --- .../data/SavingAccountForLookup.java | 20 - .../data/SavingAccountTransactionsData.java | 38 - .../data/SavingPermissionData.java | 62 - .../data/SavingScheduleData.java | 51 - .../data/SavingSchedulePeriodData.java | 53 - .../domain/DepositScheduleDateGenerator.java | 16 - .../ReccuringDepositInterestCalculator.java | 118 - .../savingsaccount/domain/SavingAccount.java | 730 ----- .../domain/SavingAccountTransaction.java | 96 - .../domain/SavingScheduleInstallments.java | 109 - .../SavingAccountNotFoundException.java | 15 - .../ApproveSavingAccountCommandHandler.java | 24 - .../CreateSavingAccountCommandHandler.java | 25 - .../DeleteSavingAccountCommandHandler.java | 25 - .../DepositSavingAmountCommandHandler.java | 25 - .../RejectSavingAccountCommandHandler.java | 25 - ...doApprovalSavingAccountCommandHandler.java | 25 - .../UpdateSavingAccountCommandHandler.java | 25 - .../WithdrawSavingAmountCommandHandler.java | 24 - ...thdrawSavingApplicationCommandHandler.java | 25 - ...eSavingScheduleQueryFromApiJsonHelper.java | 131 - ...AccountCommandFromApiJsonDeserializer.java | 216 -- ...nsitionCommandFromApiJsonDeserializer.java | 153 - .../service/CalculateSavingSchedule.java | 14 - .../service/CalculateSavingScheduleImpl.java | 42 - .../DefaultDepositScheduleDateGenerator.java | 57 - .../service/SavingAccountAssembler.java | 512 --- .../SavingAccountReadPlatformService.java | 35 - .../SavingAccountReadPlatformServiceImpl.java | 342 -- .../SavingAccountWritePlatformService.java | 36 - ...WritePlatformServiceJpaRepositoryImpl.java | 327 -- .../service/SavingScheduleAssembler.java | 139 - .../service/SavingScheduleGenerator.java | 130 - .../api/SavingProductsApiResource.java | 207 -- .../data/SavingProductData.java | 279 -- .../data/SavingProductLookup.java | 37 - .../domain/SavingFrequencyType.java | 59 - .../SavingInterestCalculationMethod.java | 58 - .../domain/SavingProduct.java | 142 - .../domain/SavingProductRelatedDetail.java | 310 -- .../domain/SavingProductRepository.java | 13 - .../domain/SavingProductType.java | 55 - .../domain/SavingsInterestType.java | 46 - .../domain/SavingsLockinPeriodEnum.java | 55 - .../UpdateSavingProductCommandHandler.java | 24 - ...ProductCommandFromApiJsonDeserializer.java | 214 -- .../service/SavingProductEnumerations.java | 193 -- .../SavingProductReadPlatformService.java | 22 - .../SavingProductReadPlatformServiceImpl.java | 180 -- ...WritePlatformServiceJpaRepositoryImpl.java | 117 - .../service/SavingsDepositEnumerations.java | 40 - .../api/DepositAccountsApiResource.java | 281 -- .../command/DepositAccountCommand.java | 200 -- .../DepositAccountCommandValidator.java | 85 - ...DepositAccountWithdrawInterestCommand.java | 33 - .../DepositAccountWithdrawalCommand.java | 33 - ...ositAccountWithdrawalCommandValidator.java | 35 - ...DepositStateTransitionApprovalCommand.java | 77 - ...ateTransitionApprovalCommandValidator.java | 42 - .../DepositStateTransitionCommand.java | 35 - ...epositAccountInterestCommandValidator.java | 35 - .../data/DepositAccountData.java | 650 ---- .../data/DepositAccountTransactionData.java | 64 - .../data/DepositAccountsForLookup.java | 21 - .../data/DepositPermissionData.java | 65 - .../domain/DepositAccount.java | 873 ------ .../domain/DepositAccountEvent.java | 11 - .../domain/DepositAccountStatus.java | 99 - .../domain/DepositAccountTransaction.java | 141 - .../domain/DepositAccountTransactionType.java | 74 - .../domain/DepositLifecycleStateMachine.java | 11 - .../DepositLifecycleStateMachineImpl.java | 119 - .../FixedTermDepositInterestCalculator.java | 95 - ...DepositAccounDataValidationtException.java | 19 - .../DepositAccountReopenException.java | 16 - .../DepositAccountTransactionsException.java | 15 - ...nvalidDepositStateTransitionException.java | 16 - ...InvalidSavingStateTransitionException.java | 11 - .../ApproveDepositAccountCommandHandler.java | 24 - .../CreateDepositAccountCommandHandler.java | 25 - .../DeleteDepositAccountCommandHandler.java | 26 - .../RejectDepositAccountCommandHandler.java | 25 - .../RenewDepositAccountCommandHandler.java | 26 - ...oApprovalDepositAccountCommandHandler.java | 25 - .../UpdateDepositAccountCommandHandler.java | 26 - ...ApplicantDepositAccountCommandHandler.java | 26 - ...rawDepositAccountAmountCommandHandler.java | 27 - ...estDepositAccountAmountCommandHandler.java | 26 - ...AccountCommandFromApiJsonDeserializer.java | 247 -- ...nsitionCommandFromApiJsonDeserializer.java | 115 - .../service/DepositAccountAssembler.java | 521 --- .../service/DepositAccountEnumerations.java | 61 - .../DepositAccountReadPlatformService.java | 29 - ...DepositAccountReadPlatformServiceImpl.java | 326 -- ...DepositAccountTransactionEnumerations.java | 48 - .../DepositAccountWritePlatformService.java | 38 - ...WritePlatformServiceJpaRepositoryImpl.java | 405 --- ...epositStateTransitionCommandValidator.java | 35 - .../service/GeneratePDF.java | 78 - .../RenewDepositAccountCommandValidator.java | 51 - .../command/DepositProductCommand.java | 251 -- .../data/DepositProductData.java | 254 -- .../data/DepositProductLookup.java | 26 - .../domain/DepositProduct.java | 450 --- .../domain/DepositProductRepository.java | 15 - .../domain/TenureTypeEnum.java | 54 - .../DepositProductNotFoundException.java | 17 - ...ositProductValueOutsideRangeException.java | 20 - .../CreateDepositProductCommandHandler.java | 24 - .../DeleteDepositProductCommandHandler.java | 25 - .../UpdateDepositProductCommandHandler.java | 25 - ...ProductCommandFromApiJsonDeserializer.java | 258 -- .../DepositProductCommandValidator.java | 102 - .../DepositProductReadPlatformService.java | 23 - ...DepositProductReadPlatformServiceImpl.java | 161 - .../DepositProductWritePlatformService.java | 18 - ...WritePlatformServiceJpaRepositoryImpl.java | 147 - .../useradministration/domain/AppUser.java | 6 +- 172 files changed, 3863 insertions(+), 16432 deletions(-) create mode 100644 mifosng-db/patches/3-drop-hugo-savings-schema-replace-with-basic-savings-schema.sql create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsApiConstants.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsdepositproduct/api/DepositProductsApiResource.java => savings/api/SavingsProductsApiResource.java} (52%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsaccount/domain/SavingAccountRepository.java => savings/domain/SavingsAccountRepository.java} (65%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsdepositaccount/domain/DepositAccountRepository.java => savings/domain/SavingsProductRepository.java} (64%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/InvalidSavingsProductSettingsException.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsdepositaccount/exception/DepositAccountNotFoundException.java => savings/exception/SavingsAccountNotFoundException.java} (52%) rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsaccountproduct/exception/SavingProductNotFoundException.java => savings/exception/SavingsProductNotFoundException.java} (66%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsAccountCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsProductCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsAccountCommandHandler.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsaccountproduct/handler/CreateSavingProductCommandHandler.java => savings/handler/DeleteSavingsProductCommandHandler.java} (51%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsAccountCommandHandler.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsaccountproduct/handler/DeleteSavingProductCommandHandler.java => savings/handler/UpdateSavingsProductCommandHandler.java} (51%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsEnumerations.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformService.java create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java rename mifosng-provider/src/main/java/org/mifosplatform/portfolio/{savingsaccountproduct/service/SavingProductWritePlatformService.java => savings/service/SavingsProductWritePlatformService.java} (50%) create mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/api/SavingsAccountApiResource.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountForLookup.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountTransactionsData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingPermissionData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingScheduleData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingSchedulePeriodData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/DepositScheduleDateGenerator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/ReccuringDepositInterestCalculator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccount.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountTransaction.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingScheduleInstallments.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/exception/SavingAccountNotFoundException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/ApproveSavingAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/CreateSavingAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DeleteSavingAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DepositSavingAmountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/RejectSavingAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UndoApprovalSavingAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UpdateSavingAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingAmountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingApplicationCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/CalculateSavingScheduleQueryFromApiJsonHelper.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountCommandFromApiJsonDeserializer.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountStateTransitionCommandFromApiJsonDeserializer.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingSchedule.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingScheduleImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/DefaultDepositScheduleDateGenerator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountAssembler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformServiceImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformServiceJpaRepositoryImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleAssembler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleGenerator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/api/SavingProductsApiResource.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductLookup.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingFrequencyType.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingInterestCalculationMethod.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProduct.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRelatedDetail.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRepository.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductType.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsInterestType.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsLockinPeriodEnum.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/UpdateSavingProductCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/serialization/SavingProductCommandFromApiJsonDeserializer.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductEnumerations.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformServiceImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformServiceJpaRepositoryImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingsDepositEnumerations.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/api/DepositAccountsApiResource.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommand.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawInterestCommand.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommand.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommand.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionCommand.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/WithDrawDepositAccountInterestCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountTransactionData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountsForLookup.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositPermissionData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccount.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountEvent.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountStatus.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransaction.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransactionType.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachine.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachineImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/FixedTermDepositInterestCalculator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccounDataValidationtException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountReopenException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountTransactionsException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidDepositStateTransitionException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidSavingStateTransitionException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/ApproveDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/CreateDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/DeleteDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RejectDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RenewDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UndoApprovalDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UpdateDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithDrawByApplicantDepositAccountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawDepositAccountAmountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawInterestDepositAccountAmountCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountCommandFromApiJsonDeserializer.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountStateTransitionCommandFromApiJsonDeserializer.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountAssembler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountEnumerations.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformServiceImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountTransactionEnumerations.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositStateTransitionCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/GeneratePDF.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/RenewDepositAccountCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/command/DepositProductCommand.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductData.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductLookup.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProduct.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProductRepository.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/TenureTypeEnum.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductNotFoundException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductValueOutsideRangeException.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/CreateDepositProductCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/DeleteDepositProductCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/UpdateDepositProductCommandHandler.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/serialization/DepositProductCommandFromApiJsonDeserializer.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductCommandValidator.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformServiceImpl.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformService.java delete mode 100644 mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformServiceJpaRepositoryImpl.java diff --git a/api-docs/apiLive.htm b/api-docs/apiLive.htm index e072939d0..56a85fb6c 100644 --- a/api-docs/apiLive.htm +++ b/api-docs/apiLive.htm @@ -632,38 +632,6 @@ Update a Charge Delete a Charge - - DEPOSIT PRODUCT - depositproducts - Create a Deposit product - List Deposit products - - - - - - depositproducts/{prodcutId} - - Retrieve a Deposit product - Update a Deposit product - Delete a Deposit product - - - SAVING PRODUCT - savingproducts - Create a Saving product - List Saving products - - - - - - savingproducts/{prodcutId} - - Retrieve a Saving product - Update a Saving product - Delete a Saving product - @@ -1082,6 +1050,7 @@ +

Template

@@ -1106,154 +1075,45 @@ clients/template - Retrieve Client Details Template + Retrieve Client Template + + + loanproducts/template + Retrieve Loan Product Template loans/template?clientId={clientId} - Retrieve Loan Details Template + Retrieve Loan Template loans/{loanId}/transactions/template Retrieve Loan Transaction Template - - offices/template - Retrieve Office Details - Template + + savingproducts/template + Retrieve Savings Product Template - loanproducts/template - Retrieve Loan - Product Details Template + savingsaccounts/template?clientId={clientId} + Retrieve Savings Account Template + + + offices/template + Retrieve Office Template users/template - Retrieve User Details - Template + Retrieve User Template audit/searchtemplate - Retrieve Audit - Search Data - - - depositproducts/template - Retrieve Deposit - Product Details Template - - - savingproducts/template - Retrieve Saving - Product Details Template - - - depositaccounts/template - Retrieve Deposit - Account Details Template - - - savingaccounts/template - Retrieve Saving - Account Details Template - - -
-
- -
-

Savings

-
+

Accounting

@@ -2926,18 +2786,6 @@ DELETE groups/7 Optional: For marking a loan with a given loan purpose option. Loan purposes are configurable and can be setup by system admin through code/code values screens. - - currencyCode - - - A three letter ISO code of currency. - - - digitsAfterDecimal - - - Override the currency default value for digitsAfterDecimal. - principal @@ -4961,846 +4809,7 @@ No Request Body:
- - -  -
-
-

Fixed Deposit Account:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Field Descriptions
deposit :
The amount to be deposited in the deposit account.
externalId :
A place to put an external reference for this deposit account. e.g. The ID another system uses.
- If provided, it must be unique.
tenureInMonths:
The time period for fixed deposit to mature(in months).
- Eg:The period of deposit shall be 24 months
- tenureInMonths=24. -
renewalAllowed:
Used to renew the deposit account after maturity. -
if 'true' the account is eligible for renew. -
isInterestWithdrawable:
Denotes whether one can withdraw the interest from deposit account.
interestCompoundingAllowed:
Denotes whether the interest is calculated on compounding basis or not.
- if true:interest calculated on compounding basis, else interest calculated on simple calculation basis. -
maturityInterestRate:
Denotes the interest rate % on deposit amount.
preClosureInterestRate:
Denotes the interest rate % of deposit amount for preclosing accounts.
- This rate is applicable if the account is preclosed. -
interestCompoundedEvery:
Interest is calculated on deposit amount for every interestCompoundedEvery period
lockinPeriod:
Defines a lockin period for deposit account.
- With in the lockin period one cannot preclose the deposit account. -
-
-
- - -  -
-
-

Retrieve Deposit Account Details Template:

-

This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of: -

    -
  • Field Defaults
  • -
  • Allowed Value Lists
  • -
-

-

Arguments

-
-
clientId
-
Integer mandatory
-
productId
-
Integer optional
-
If entered productId, productName and selectedProduct fields are returned.
-
-

Example Requests:

-
depositaccounts/template?clientId=17&productId=1
-

-
depositaccounts/template?clientId=17
-
-
- GET https://Domain Name/api/v1/depositaccounts/template?clientId={clientId}&productId={productId} - -{ - "clientId": 1, - "clientName": "First Client", - "productId": 1, - "productName": "MyFirstDepositProduct", - "currency": { - "code": "USD", - "name": "", - "decimalPlaces": 2, - "displaySymbol": "", - "nameCode": "", - "displayLabel": " [USD]" - }, - "deposit": 100, - "maturityInterestRate": 6, - "tenureInMonths": 12, - "projectedCommencementDate": [ - 2013, - 2, - 6 - ], - "interestCompoundedEvery": 1, - "interestCompoundedEveryPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "renewalAllowed": true, - "preClosureAllowed": true, - "preClosureInterestRate": 3, - "isInterestWithdrawable": false, - "interestCompoundingAllowed": true, - "interestCompoundedEveryPeriodTypeOptions": [ - { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - } - ], - "productOptions": [ - { - "id": 1, - "name": "MyFirstDepositProduct" - } - ], - "availableInterestForWithdrawal": 0, - "availableWithdrawalAmount": 0, - "todaysDate": [ - 2013, - 2, - 6 - ], - "isLockinPeriodAllowed": true, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "availableInterest": 0, - "interestPostedAmount": 0 -} - - - GET https://Domain Name/api/v1/depositaccounts/template?clientId={clientId} -{ - "clientId": 1, - "clientName": "First Client", - "renewalAllowed": false, - "preClosureAllowed": false, - "isInterestWithdrawable": false, - "interestCompoundingAllowed": true, - "interestCompoundedEveryPeriodTypeOptions": [ - { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - } - ], - "productOptions": [ - { - "id": 1, - "name": "MyFirstDepositProduct" - } - ], - "availableInterestForWithdrawal": 0, - "availableWithdrawalAmount": 0, - "todaysDate": [ - 2013, - 2, - 6 - ], - "isLockinPeriodAllowed": true, - "availableInterest": 0, - "interestPostedAmount": 0 -} - -
-
- -  -
-
-

Retrieve a fixeddeposit:

- -

Arguments

-
-
associations
-
optional, 'all' deposit associations are itemised below
-

Associations are just extra pieces of data that you might or might not want to retrieve.

-
'all': Gets all association data.
-
'permissions': Data that describes what things can happen to the deposit in its current state. - Very specific to the needs of the current Individual Lending client application.
-
-

Example Requests:

-
depositaccounts/1
-

-
depositaccounts/1?associations=all
-
-
- GET https://DomainName/api/v1/depositaccounts/{depositaccountId} - { -{ - "id": 5, - "status": { - "id": 100, - "code": "depositStatusType.submitted.and.pending.approval", - "value": "Submitted and pending approval" - }, - "clientId": 17, - "clientName": "Agri", - "productId": 1, - "productName": "Micro Savings", - "currency": { - "code": "INR", - "name": "Indian Rupee", - "decimalPlaces": 2, - "nameCode": "currency.INR", - "displayLabel": "Indian Rupee [INR]" - }, - "deposit": 200.000000, - "maturityInterestRate": 12.000000, - "tenureInMonths": 12, - "projectedCommencementDate": [2012, 12, 16], - "maturedOn": [2013, 12, 15], - "projectedInterestAccrued": 24.000000, - "projectedMaturityAmount": 224.000000, - "interestCompoundedEvery": 6, - "interestCompoundedEveryPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "renewalAllowed": true, - "preClosureAllowed": true, - "preClosureInterestRate": 5.000000, - "isInterestWithdrawable": true, - "interestPaid": 0.000000, - "interestCompoundingAllowed": false, - "permissions": { - "rejectAllowed": true, - "withdrawnByApplicantAllowed": true, - "undoApprovalAllowed": false, - "pendingApproval": true, - "isInterestWithdrawalAllowed": true, - "renewelAllowed": false, - "isMaturedDepositAccount": false, - "anyActionOnAccountAllowed": true - }, - "availableInterestForWithdrawal": 0, - "availableWithdrawalAmount": 200.000000, - "todaysDate": [2013, 1, 30], - "isLockinPeriodAllowed": true, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "availableInterest": 0.000000, - "interestPostedAmount": 0.000000, - "imageKey": "/root/.mifosx/DefaultDemoTenant/images/clients/33/places.png" -} -} - -
-
- -  -
-
-

Create a New DepositAccount / Submit a DepositAccount Application

-

Arguments

-
-
command
-
String Optional, case-insensitive
-
The default action is to Submit a New DepositAccount Application ("Submitted and awaiting approval" status).
-
-
- - - -
Mandatory Fields
clientId, productId, deposit, maturityInterestRate, commencementDate
-
-
- POST https://Domain Name/api/v1/depositaccounts - POST depositaccount -Content-Type: application/json -Request Body: -{ - "clientId": "17", - "dateFormat": "dd MMMM yyyy", - "locale": "en", - "productId": "1", - "commencementDate": "25 January 2013", - "externalId": "123", - "deposit": "20000", - "tenureInMonths": "3", - "renewalAllowed": "true", - "preClosureAllowed": "true", - "interestCompoundingAllowed": "false", - "isInterestWithdrawable": "true", - "isLockinPeriodAllowed": "true", - "maturityInterestRate": "12", - "preClosureInterestRate": "5", - "interestCompoundedEvery": "6", - "interestCompoundedEveryPeriodType": "2", - "lockinPeriod": "1", - "lockinPeriodType": "2" -} - - - { - "resourceId": 42 -} - -
-
- -   -
-
-

Approval, Reject or Withdraw a DepositAccount Application

-

Arguments

-
-
command
-
String Mandatory, case-insensitive
-
'approve' : Approve DepositAccount
-
'reject' : Reject DepositAccount
-
'withdrewbyclient' : Client Withdrew DepositAccount Application
-
Deposit amount
-
IntegerMandatory
-
Deposit interest rate
-
IntegerMandatory
-
Tenure month
-
IntegerMandatory
-
Interest posted every
-
IntegerMandatory
-
-
- - - -
Mandatory Fields
eventDate
-
-
- POST https://DomainName/api/v1/depositaccounts/{depositaccountId} - POST depositaccounts/1?command=reject -Content-Type: application/json -Request Body: -{ - "dateFormat": "dd MMMM yyyy", - "eventDate": "07 May 2012", - "note": "and event note is added" -} - -{ -"resourceId": 37 -} - -
-
-   -
-
-

Delete a DepositAccount

-

- Note: depositaccount is deleted. -

-
-
- DELETE https://Domain Name/api/v1/depositaccounts/{depositaccountsId} - DELETE depositaccounts/1 -Content-Type: application/json -No Request Body: - - { -"resourceId": 1 -} - -
-
- - -  -
-
-

Saving Account :

- - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
Field Descriptions
savingsDepositAmountPerPeriod :
The amount to be depositd in the savingaccount for every period.
- If the account is regular account enter what ever the amount you want to deposit
externalId :
A place to put an external reference for this savingaccount. e.g. The ID another system uses.
- If provided, it must be unique.
tenure :
denotes the tenure period of savings account
depositEvery :
For every 'depositEvery' period the client has to deposit 'savingsDepositAmountPerPeriod' amount
interestCalculationMethod:
denotes on what basis the interest is calculated
- e.g. AverageBal,Monthly Collection etc
recurringInterestRate :
The interest rate applicable on recurring deposit savingaccounts
savingInterestRate :
The interest rate applicable on regular savingaccounts
interestPostEvery:
Denotes for how many months the interest is posted for recurring/regular saving accounts
lockinPeriod :
With in a lockin period you cannot withdraw whole money(cannot Preclose)
-
-
- - -  -
-
-

Retrieve SavingAccount Details Template :

-

This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of: -

    -
  • Field Defaults
  • -
  • Allowed Value Lists
  • -
-

-

Arguments

-
-
clientId
-
Integer mandatory
-
productId
-
Integer optional
-
If entered, productId, productName and selectedProduct fields are returned.
-
-

Example Requests:

-
savingaccounts/template?clientId=25&productId=5
-

-
savingaccounts/template?clientId=25
-
-
- GET https://Domain Name/api/v1/savingaccounts/template -{ - "clientId": 25, - "clientName": "Clark Kent", - "productId": 5, - "productName": "Shares", - "productType": { - "id": 2, - "code": "savings.product.savingProductType.regular", - "value": "Regular" - }, - "currencyData": { - "code": "ZAR", - "name": "South African Rand", - "decimalPlaces": 2, - "displaySymbol": "R", - "nameCode": "currency.ZAR", - "displayLabel": "South African Rand (R)" - }, - "savingsDepositAmountPerPeriod": 500.000000, - "savingsFrequencyType": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }, - "recurringInterestRate": 12.000000, - "savingInterestRate": 12.000000, - "interestType": { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }, - "interestCalculationMethod": { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - "tenure": 12, - "tenureType": { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - "projectedCommencementDate": [2013, - 2, - 1], - "preClosureAllowed": true, - "isLockinPeriodAllowed": false, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "depositEvery": 1, - "productOptions": [{ - "id": 4, - "name": "sb01" - }, - { - "id": 5, - "name": "Shares" - }], - "currencyOptions": [{ - "code": "ZAR", - "name": "South African Rand", - "decimalPlaces": 2, - "displaySymbol": "R", - "nameCode": "currency.ZAR", - "displayLabel": "South African Rand (R)" - }, - { - "code": "VND", - "name": "Vietnamese Dong", - "decimalPlaces": 2, - "nameCode": "currency.VND", - "displayLabel": "Vietnamese Dong [VND]" - }], - "savingsProductTypeOptions": [{ - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" - }, - { - "id": 2, - "code": "savings.product.savingProductType.regular", - "value": "Regular" - }], - "tenureTypeOptions": [{ - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - { - "id": 2, - "code": "savings.tenure.tenureTypeEnum.perpetual", - "value": "Perpetual" - }], - "savingFrequencyOptions": [{ - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }], - "savingsInterestTypeOptions": [{ - "id": 1, - "code": "savings.interest.type.savingsInterestType.simple", - "value": "Simple" - }, - { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }], - "lockinPeriodTypeOptions": [{ - "id": 2, - "code": "savings.product.lockin.period.type.months", - "value": "Months" - }], - "interestCalculationOptions": [{ - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - { - "id": 3, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.monthlycllection", - "value": "MonthlyCollection" - }], - "outstandingAmount": 0, - "dueAmount": 0, - "interestPostEvery": 3, - "interestPostFrequency": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - } -} - - -
-
- -  -
-
-

Retrieve a SavingAccount :

-

- Note: template=true parameter doesn't apply to this resource. -

-

Arguments

-
-
associations
-
optional, Either 'all' or a comma separated list of savings 'associations' (itemised below).
-

Associations are just extra pieces of data that you might or might not want to retrieve.

-
'all': Gets all association data.
-
'permissions': Data that describes what things can happen to the saving account in its current state. - Very specific to the needs of the current Individual Lending client application.
-
'savingScheduleData': Some derived data that
-
'transactions' : Some data
-
-

Example Requests :

-
savingaccounts/15
-

-
savingaccounts/15?associations=all
-
-
- GET https://DomainName/api/v1/savingaccounts/{savingaccountId} - { - "id": 15, - "status": { - "id": 100, - "code": "depositStatusType.submitted.and.pending.approval", - "value": "Submitted and pending approval" - }, - "externalId": "23", - "clientId": 50, - "clientName": "Brendan Fahy", - "productId": 4, - "productName": "sb01", - "productType": { - "id": 2, - "code": "savings.product.savingProductType.regular", - "value": "Regular" - }, - "currencyData": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "savingsDepositAmountPerPeriod": 200.000000, - "savingsFrequencyType": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }, - "totalDepositAmount": 0.000000, - "recurringInterestRate": 4.000000, - "savingInterestRate": 4.000000, - "interestType": { - "id": 1, - "code": "savings.interest.type.savingsInterestType.simple", - "value": "Simple" - }, - "interestCalculationMethod": { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - "tenure": 12, - "tenureType": { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - "projectedCommencementDate": [2013, - 2, - 1], - "projectedInterestAccuredOnMaturity": 0.000000, - "actualInterestAccured": 0.000000, - "projectedMaturityAmount": 200.000000, - "actualMaturityAmount": 0.000000, - "preClosureAllowed": false, - "preClosureInterestRate": 0.000000, - "isLockinPeriodAllowed": false, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "savings.product.lockin.period.type.months", - "value": "Months" - }, - "depositEvery": 1, - "permissions": { - "rejectAllowed": true, - "withdrawnByApplicantAllowed": true, - "undoApprovalAllowed": false, - "pendingApproval": true, - "renewelAllowed": false, - "isMaturedDepositAccount": false, - "anyActionOnAccountAllowed": true - }, - "outstandingAmount": 0.000000, - "savingScheduleData": { - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "cumulativeDepositDue": 200.0000, - "cumulativeDepositPaid": 0.0000, - "cummulativeInterestAccured": 0.0000, - "periods": [{ - "period": 1, - "dueDate": [2013, - 3, - 1], - "depositDue": 200.0000, - "depositPaid": 0.0000, - "interestAccured": 0.0000 - }] - }, - "transactions": [], - "interestPostEvery": 3, - "interestPostFrequency": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - } -} - -
-
- -  -
-
-

Create a New SavingAccount / Submit a SavingAccount Application

-

Arguments

-
-
command
-
String Optional, case-insensitive
-
The default action is to Submit a New SavingAccount Application ("Submitted and awaiting approval" status).
-
-
- - - -
Mandatory Fields
clientId, productId, savingsDepositAmountPerPeriod, tenureMonths, depositEvery, interestCalculationMethod, recurringInterestRate, commencementDate, interestPostEvery
-
-
- POST https://Domain Name/api/v1/savingaccounts - POST savingaccount -Content-Type: application/json -Request Body: -{ - "clientId": "17", - "dateFormat": "dd MMMM yyyy", - "locale": "en", - "currencyCode": "ZAR", - "digitsAfterDecimal": "2", - "productId": "5", - "commencementDate": "05 February 2013", - "externalId": "", - "savingsDepositAmountPerPeriod": "500", - "minimumBalanceForWithdrawal": "100", - "tenure": "12", - "tenureType": "1", - "depositEvery": "1", - "frequency": "2", - "isLockinPeriodAllowed": "false", - "isPartialDepositAllowed": "false", - "interestCalculationMethod": "1", - "recurringInterestRate": "12", - "interestType": "2", - "savingInterestRate": "12", - "interestPostEvery": "3", - "interestPostFrequency": "2", - "lockinPeriod": "0", - "lockinPeriodType": "2" -} - { - "resourceId": 42 -} - -
-
- -   -
-
-

Approval, Reject or Withdraw a SavingAccount Application

-

Arguments

-
-
command
-
String Mandatory, case-insensitive
-
'approve' : Approve SavingAccount
-
'reject' : Reject SavingAccount
-
'withdrewbyclient' : Client Withdrew SavingAccount Application
-
-
- - - -
Mandatory Fields
eventDate
-
-
- POST https://Domain Name/api/v1/savingaccounts/{savingaccountId} - POST savingaccounts/1?command=reject -Content-Type: application/json -Request Body: -{ - "dateFormat": "dd MMMM yyyy", - "eventDate": "07 May 2012", - "note": "and event note is added" -} - -{ -"resourceId": 37 -} - -
-
-   -
-
-

Delete a SavingAccount

-

- Note: savingaccount is deleted. -

-
-
- DELETE https://Domain Name/api/v1/savingaccounts/{savingaccountsId} - DELETE savingaccounts/1 -Content-Type: application/json -No Request Body: - - { -"resourceId": 1 -} - -
-
- - - - +  
@@ -7796,811 +6805,78 @@ Content-Type: application/json { "resourceId": 1 }
- - -   -
-
-

Deposit Products :

-

A Deposit product is a template that is used when creating a Fixed Deposit Account. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Field Descriptions
name
The name of the product offering.
description
Used to provide extra textual information about the product.
digitsAfterDecimal
Override the currency default value for digitsAfterDecimal.
minDeposit
The minimum amount allowed when opening a deposit account.
maxDeposit
The maximum amount allowed when opening a deposit account.
defaultDeposit
The amount presented by default when opening a deposit account.
tenureInMonths
The duration for fixed deposit (in months).
- e.g. 12 -
minInterestRate
The minimum allowed interest rate for this product.
- e.g. 1.5
maxInterestRate
The maximum allowed interest rate for this product.
- e.g. 11.5
defaultInterestRate
The interest rate presented by default when opening an account.
- e.g. 6.5
interestCompoundedEvery
Interest amount which is accrued or earned during the tenure of the deposit account will be posted to customer as interest as per the selected period in "interestCompoundedEvery" and combination of "interestCompoundedEveryPeriodType"
- e.g.Every 1-Month
interestCompoundedEveryPeriodType
Denotes the interest compounding period type, used with combination of interestCompoundedEvery
- e.g. Days=0, Weeks=1, Months=2, Years=3
renewalAllowed
Indicates whether accounts are allowed to be renewed on maturity.
- Used like: renewalAllowed:true
preClosureAllowed
Indicates whether accounts are allowed to be closed before maturity.
- If 'true' : Closure before maturity is allowed; otherwise closure before maturity is not allowed.
preClosureInterestRate
The interest rate used in cases where pre-closure occurs. Mandatory if preClosureAllowed=true
interestCompoundingAllowed
Denotes whether the interest is calculated using simple interest or compounding interest.
isLockinPeriodAllowed
This will allow to set the lock-in period for a fixed deposit product
- If 'true' :isLockinPeriodAllowed otherwise isLockinPeriod not allowed
lockinPeriod
Defines a lock-in period for deposit account.
-
-
- -   -
-
-

List DepositProducts

-

Example Requests:

-
depositproducts
-

-
depositproducts?fields=name, ......
-
-
- GET https://Domain Name/api/v1/depositproducts - -[{ - "id": 1, - "name": "Test", - "description": "asdf", - "currencyCode": "USD", - "digitsAfterDecimal": 2, - "minimumBalance": 100.000000, - "maximumBalance": 1000.000000, - "tenureInMonths": 12, - "maturityDefaultInterestRate": 12.000000, - "maturityMinInterestRate": 8.000000, - "maturityMaxInterestRate": 12.000000, - "interestCompoundedEvery": 1, - "interestCompoundedEveryPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "renewalAllowed": false, - "preClosureAllowed": false, - "preClosureInterestRate": 6.000000, - "interestCompoundingAllowed": true, - "isLockinPeriodAllowed": false, - "lockinPeriod": 2, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "createdOn": 1360576753000, - "lastModifedOn": 1360579312000 -}...] - -
-
- -   -
-
-

Retrieve DepositProduct Details Template

-

This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of: -

    -
  • Field Defaults
  • -
  • Allowed Value Lists
  • -
-

-

Example Request:

-
depositproducts/template
-
-
- GET https://Domain Name/api/v1/depositproducts/template - -{ - "interestCompoundedEveryPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "renewalAllowed": false, - "preClosureAllowed": false, - "isLockinPeriodAllowed": false, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "currencyOptions": [{ - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }], - "interestCompoundedEveryPeriodTypeOptions": [{ - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }] -} - -
-
- -   -
-
-

Retrieve a Deposit Product

-

Example Requests:

-
depositproducts/1
-

-
depositproducts/1?template=true
-

-
depositproducts/1?fields=name,description
-
-
- GET https://Domain Name/api/v1/depositproducts/1 - -{ - "id": 1, - "name": "Test", - "description": "asdf", - "currencyCode": "USD", - "digitsAfterDecimal": 2, - "minimumBalance": 100, - "maximumBalance": 1000, - "tenureInMonths": 12, - "maturityDefaultInterestRate": 12, - "maturityMinInterestRate": 8, - "maturityMaxInterestRate": 12, - "interestCompoundedEvery": 1, - "interestCompoundedEveryPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "renewalAllowed": false, - "preClosureAllowed": false, - "preClosureInterestRate": 6, - "interestCompoundingAllowed": true, - "isLockinPeriodAllowed": false, - "lockinPeriod": 2, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "createdOn": 1360576753000, - "lastModifedOn": 1360579312000 -} - + +   +
+
+

Savings Product:

+

An MFIs savings product offerings are modelled using this API.

+

When creating savings accounts, the details from the savings product are used to autofill details of savings account.

+ + - GET https://Domain Name/api/v1/depositproducts/1?template=true - -{ - "id": 1, - "name": "Test", - "description": "asdf", - "currencyCode": "USD", - "digitsAfterDecimal": 2, - "minimumBalance": 100.000000, - "maximumBalance": 1000.000000, - "tenureInMonths": 12, - "maturityDefaultInterestRate": 12.000000, - "maturityMinInterestRate": 8.000000, - "maturityMaxInterestRate": 12.000000, - "interestCompoundedEvery": 1, - "interestCompoundedEveryPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "renewalAllowed": false, - "preClosureAllowed": false, - "preClosureInterestRate": 6.000000, - "interestCompoundingAllowed": true, - "isLockinPeriodAllowed": false, - "lockinPeriod": 2, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "createdOn": 1360576753000, - "lastModifedOn": 1360579312000, - "currencyOptions": [{ - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }], - "interestCompoundedEveryPeriodTypeOptions": [{ - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }] -} - - - - -   -
-
-

Create a Deposit Product

-
Field Descriptions
- - - - -
Mandatory Fields
name, currencyCode, digitsAfterDecimal,interestPostedEvery, minimumBalance, -
- tenureInMonths, maturityDefaultInterestRate,maturityMinInterestRate, -
- maturityMaxInterestRate,interestCompoundedEvery,preClosureInterestRate. -
-
-
- POST https://Domain Name/api/v1/depositproducts - POST depositproducts -Content-Type: application/json -Request Body: -{ - "locale": "en", - "name": "Test", - "description": "asdf", - "currencyCode": "USD", - "digitsAfterDecimal": "2", - "minimumBalance": "100", - "maximumBalance": "1,000", - "tenureInMonths": "12", - "renewalAllowed": "true", - "preClosureAllowed": "false", - "interestCompoundingAllowed": "true", - "isLockinPeriodAllowed": "false", - "maturityDefaultInterestRate": "12", - "maturityMinInterestRate": "8", - "maturityMaxInterestRate": "12", - "preClosureInterestRate": "6", - "interestCompoundedEvery": "1", - "interestCompoundedEveryPeriodType": "2", - "lockinPeriod": "2", - "lockinPeriodType": "2" -} - - { - "resourceId": 1 -} - -
-
- -   -
-
-

Update a Deposit Product

-
-
- PUT https://Domain Name/api/v1/depositproducts/{depositId} - POST depositproducts/1 -Content-Type: application/json -Request Body: -{ - "locale": "en", - "description": "Update desc" -} - - { - "resourceId": 1 -} - -
-
- -   -
-
-

Delete a Deposit Product

-

Deletes a Deposit Product.

-
-
- -DELETE https://Domain Name/api/v1/depositproducts/{productId} - - -DELETE depositproducts/1 -Content-Type: application/json - - { "resourceId": 1 } -
-
- + name + The name of the product offering. - - -   -
-
-

Saving Products :

-

A Saving product is a template that is used when creating a Saving Account. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Field Descriptions
digitsAfterDecimal
Override the currency default value for digitsAfterDecimal.
savingsDepositAmount :
The deposit amount need to be deposited every depositEvery period.
minimumBalanceForWithdrawal :
The minimumbal that is need to be maintained in saving account
depositEvery:
The time period to deposit the amount to saving account every "depositEvery" "frequency"
- e.g. Every 1 Month
tenureType
This denotes the tenureType for savings account
tenure
The duration for fixed deposit (in months).
- e.g. 12 -
interestRate
Default interest rate for Saving account
- e.g. 12
interestType
Denotes the interestType for Saving account
- simple/compounding
minInterestRate
Minimum supported interest rate for Saving account
- e.g. 8
maxInterestRate
Maximum supported interest rate for Saving account
- e.g. 14
isPartialDepositAllowed
Allows to deposit the partial amount for saving account.
- Used like: isPartialDepositAllowed:true
isLockinPeriodAllowed
This will allow to set the lock-in period for a saving account
- If 'true' :isLockinPeriodAllowed otherwise isLockinPeriod not allowed
lockinPeriod
Defines a lock-in period for saving account.
savingProductType
Defines the savingProductType for saving account.
- Recurring/Regular
interestCalculationMethod
Defines the interestCalculationMethod for saving account.
- Montly Collection/Average Balance etc
-
+ description + A description of the product offering. + + currencyCode + Three letter ISO code reprsenting currency. + + digitsAfterDecimal + Override the currency default value for digitsAfterDecimal. + + interestRate + The default interest rate set when creating savings accounts of this type of product. e.g. 5% Per year + + interestRatePeriodFrequencyType + The default interest rate period type. 2=Per month, 3=Per year e.g. 5% Per year + + minRequiredOpeningBalance + Optional: If provided, sets the minimum deposit amount required to open a savings account e.g. 2,000 + + lockinPeriodFrequency + Optional: If provided, used along with lockinPeriodFrequencyType to indicate the length of time that the savings account is 'locked in' and withdrawals are not allowed. e.g. 6 Months + + lockinPeriodFrequencyType + Optional: If provided, used along with lockinPeriodFrequency to indicate the length of time that the savings account is 'locked in' and withdrawals are not allowed. 0=Days, 1=Weeks, 2=Months, 3=Years + e.g. 6 Months + +
+
+ +   +
+
+

Retrieve Savings Product Template

+

This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of: +

    +
  • Field Defaults
  • +
  • Allowed Value Lists
  • +
+

+

Example Request:

+
savingsproducts/template
- -   -
-
-

List SavingProducts

-

Example Requests:

-
savingproducts
-

-
savingproducts?fields=name, ......
-
-
- GET https://Domain Name/api/v1/savingproducts - -[{ - "id": 1, - "name": "Test", - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "digitsAfterDecimal": 2, - "interestRate": 12.000000, - "minInterestRate": 6.000000, - "maxInterestRate": 12.000000, - "savingsDepositAmount": 1000.000000, - "savingProductType": { - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" - }, - "tenureType": { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - "tenure": 12, - "savingFrequencyType": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }, - "interestType": { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }, - "interestCalculationMethod": { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - "minimumBalanceForWithdrawal": 100.000000, - "isPartialDepositAllowed": false, - "isLockinPeriodAllowed": false, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "createdOn": 1360594232000, - "lastModifedOn": 1360594232000, - "depositEvery": 3 -}] - -
-
- -   -
-
-

Retrieve SavingProduct Details Template

-

This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of: -

    -
  • Field Defaults
  • -
  • Allowed Value Lists
  • -
-

-

Example Request:

-
savingproducts/template
-
-
- GET https://Domain Name/api/v1/savingproducts/template - +
+ GET https://Domain Name/api/v1/savingsproducts/template + { - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "digitsAfterDecimal": 2, - "interestRate": 0, - "savingsDepositAmount": 0, - "savingProductType": { - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" - }, - "tenureType": { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - "tenure": 12, - "savingFrequencyType": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }, - "interestType": { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }, - "interestCalculationMethod": { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - "minimumBalanceForWithdrawal": 100, - "isPartialDepositAllowed": false, - "isLockinPeriodAllowed": false, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "savings.product.lockin.period.type.months", - "value": "Months" - }, - "createdOn": 1360596667364, - "lastModifedOn": 1360596667364, - "depositEvery": 3, - "currencyOptions": [{ - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }], - "savingsProductTypeOptions": [{ - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" - }, - { - "id": 2, - "code": "savings.product.savingProductType.regular", - "value": "Regular" - }], - "tenureTypeOptions": [{ - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - { - "id": 2, - "code": "savings.tenure.tenureTypeEnum.perpetual", - "value": "Perpetual" - }], - "savingFrequencyOptions": [{ - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }], - "savingsInterestTypeOptions": [{ - "id": 1, - "code": "savings.interest.type.savingsInterestType.simple", - "value": "Simple" - }, - { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }], - "lockinPeriodTypeOptions": [{ - "id": 2, - "code": "savings.product.lockin.period.type.months", - "value": "Months" - }], - "interestCalculationOptions": [{ - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - { - "id": 2, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.minbal", - "value": "Minimumbalance" - }, - { - "id": 3, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.monthlycllection", - "value": "MonthlyCollection" - }] -} - -
-
- -   -
-
-

Retrieve a Saving Product

-

Example Requests:

-
savingproducts/1
-

-
savingproducts/1?template=true
-

-
savingproducts/1?fields=name,description
-
-
- GET https://Domain Name/api/v1/savingproducts/1 - -{ - "id": 1, - "name": "Test", "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" + "code": "", + "name": "", + "decimalPlaces": 0, + "displaySymbol": "", + "nameCode": "", + "displayLabel": " []" }, - "digitsAfterDecimal": 2, - "interestRate": 12, - "minInterestRate": 6, - "maxInterestRate": 12, - "savingsDepositAmount": 1000, - "savingProductType": { - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" + "interestRatePeriodFrequencyType": { + "id": 3, + "code": "savings.interest.rate.periodFrequencyType.years", + "value": "Per year" }, - "tenureType": { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - "tenure": 12, - "savingFrequencyType": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }, - "interestType": { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }, - "interestCalculationMethod": { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - "minimumBalanceForWithdrawal": 100, - "isPartialDepositAllowed": false, - "isLockinPeriodAllowed": false, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "createdOn": 1360594232000, - "lastModifedOn": 1360594232000, - "depositEvery": 3 -} - - - GET https://Domain Name/api/v1/depositproducts/1?template=true - -{ - "id": 1, - "name": "Test", - "currency": { - "code": "USD", - "name": "US Dollar", - "decimalPlaces": 2, - "displaySymbol": "$", - "nameCode": "currency.USD", - "displayLabel": "US Dollar ($)" - }, - "digitsAfterDecimal": 2, - "interestRate": 12, - "minInterestRate": 6, - "maxInterestRate": 12, - "savingsDepositAmount": 1000, - "savingProductType": { - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" - }, - "tenureType": { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - "tenure": 12, - "savingFrequencyType": { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - }, - "interestType": { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - }, - "interestCalculationMethod": { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - "minimumBalanceForWithdrawal": 100, - "isPartialDepositAllowed": false, - "isLockinPeriodAllowed": false, - "lockinPeriod": 0, - "lockinPeriodType": { - "id": 2, - "code": "deposit.interest.compounding.period.periodFrequencyType.months", - "value": "Months" - }, - "createdOn": 1360594232000, - "lastModifedOn": 1360594232000, - "depositEvery": 3, "currencyOptions": [ { "code": "USD", @@ -8611,172 +6887,600 @@ Content-Type: application/json "displayLabel": "US Dollar ($)" } ], - "savingsProductTypeOptions": [ - { - "id": 1, - "code": "savings.product.savingProductType.reccuring", - "value": "Recurring" - }, + "interestRatePeriodFrequencyTypeOptions": [ { "id": 2, - "code": "savings.product.savingProductType.regular", - "value": "Regular" - } - ], - "tenureTypeOptions": [ - { - "id": 1, - "code": "savings.tenure.tenureTypeEnum.fixedPeriod", - "value": "FixedPeriod" - }, - { - "id": 2, - "code": "savings.tenure.tenureTypeEnum.perpetual", - "value": "Perpetual" - } - ], - "savingFrequencyOptions": [ - { - "id": 2, - "code": "saving.product.frequency.period.savingFrequencyType.monthly", - "value": "Months" - } - ], - "savingsInterestTypeOptions": [ - { - "id": 1, - "code": "savings.interest.type.savingsInterestType.simple", - "value": "Simple" - }, - { - "id": 2, - "code": "savings.interest.type.savingsInterestType.compounding", - "value": "Compounding" - } - ], - "lockinPeriodTypeOptions": [ - { - "id": 2, - "code": "savings.product.lockin.period.type.months", - "value": "Months" - } - ], - "interestCalculationOptions": [ - { - "id": 1, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.averagebal", - "value": "AverageBalance" - }, - { - "id": 2, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.minbal", - "value": "Minimumbalance" + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" }, { "id": 3, - "code": "savings.interestCalculation.method.savinginterest.calculation.method.monthlycllection", - "value": "MonthlyCollection" + "code": "savings.interest.rate.periodFrequencyType.years", + "value": "Per year" + } + ], + "lockinPeriodFrequencyTypeOptions": [ + { + "id": 0, + "code": "savings.lockin.periodFrequencyType.days", + "value": "Days" + }, + { + "id": 1, + "code": "savings.lockin.periodFrequencyType.weeks", + "value": "Weeks" + }, + { + "id": 2, + "code": "savings.lockin.periodFrequencyType.months", + "value": "Months" + }, + { + "id": 3, + "code": "savings.lockin.periodFrequencyType.years", + "value": "Years" } ] -} - -
+} +
- -   -
-
-

Create a Saving Product

- - - - - -
Mandatory Fields
name, currencyCode, digitsAfterDecimal,interestPostedEvery, minimumBalance, -
- tenureInMonths, maturityDefaultInterestRate,maturityMinInterestRate, -
- maturityMaxInterestRate,interestCompoundedEvery,preClosureInterestRate. -
-
-
- POST https://Domain Name/api/v1/savingproducts - POST savingproducts +
+ +   +
+
+

Create a Savings Product

+ + + +
Mandatory Fields
name, description, currencyCode, digitsAfterDecimal, interestRate, interestRatePeriodFrequencyType
+
+ + + +
Optional Fields
minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType
+
+
+ POST https://Domain Name/api/v1/savingsproducts + POST savingsproducts Content-Type: application/json Request Body: { - "locale": "en", - "interestCalculationMethod": "1", - "name": "Test", - "savingProductType": "1", - "description": "", - "currencyCode": "USD", - "digitsAfterDecimal": "2", - "savingsDepositAmount": "1000", - "minimumBalanceForWithdrawal": "100", - "tenure": "12", - "tenureType": "1", - "isLockinPeriodAllowed": "false", - "isPartialDepositAllowed": "false", - "interestRate": "12", - "interestType": "2", - "minInterestRate": "6", - "maxInterestRate": "12", - "depositEvery": "3", - "frequency": "2", - "lockinPeriod": "0", - "lockinPeriodType": "2" + "name": "individual savings", + "description": "An savings product offering for individuals.", + "currencyCode": "USD", + "digitsAfterDecimal": 2, + "locale": "en", + "interestRate": "5.65", + "interestRatePeriodFrequencyType": 2 } - - { + + +{ "resourceId": 1 } - -
+
+
+ +   +
+
+

Retrieve a Savings Product

+

Example Requests:

+
savingsproducts/1
+

+
savingsproducts/1?template=true
+

+
savingsproducts/1?fields=name,description
+
+
+ GET https://Domain Name/api/v1/savingsproducts/1 + +{ + "id": 1, + "name": "individual savings", + "description": "An savings product offering for individuals. (updated)", + "currency": { + "code": "USD", + "name": "US Dollar", + "decimalPlaces": 2, + "displaySymbol": "$", + "nameCode": "currency.USD", + "displayLabel": "US Dollar ($)" + }, + "interestRate": 5.73, + "interestRatePeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + } +} + +
+
-   -
-
-

Update a Saving Product

-
-
- PUT https://Domain Name/api/v1/savingproducts/{depositId} - POST savingproducts/1 +   +
+
+

Update a Savings Product

+
+
+ PUT https://Domain Name/api/v1/savingsproducts/{productId} + POST savingsproducts/1 Content-Type: application/json Request Body: { - "locale": "en", - "description": "Update desc" + "description": "An savings product offering for individuals. (updated)", + "locale": "en", + "interestRate": "5.73" } - - { - "resourceId": 1 + + +{ + "resourceId": 1, + "changes": { + "description": "An savings product offering for individuals. (updated)", + "interestRate": 5.73, + "locale": "en" + } } - -
+
+
-   -
-
-

Delete a Saving Product

-

Deletes a Saving Product.

-
-
- -DELETE https://Domain Name/api/v1/savingproducts/{productId} - - -DELETE savingproducts/1 +   +
+
+

Delete a Savings Product

+
+
+ +DELETE https://Domain Name/api/v1/savingsproducts/{productId} + + +DELETE savingsproducts/1 Content-Type: application/json - - { "resourceId": 1 } -
-
- +
+ +{ + "resourceId": 1 +} + +
+
- +   +
+
+

List Savings Products

+

Example Requests:

+
savingsproducts
+

+
savingsproducts?fields=name
+
+
+ GET https://Domain Name/api/v1/savingsproducts + +[ + { + "id": 1, + "name": "individual savings", + "description": "An savings product offering for individuals. (updated)", + "currency": { + "code": "USD", + "name": "US Dollar", + "decimalPlaces": 2, + "displaySymbol": "$", + "nameCode": "currency.USD", + "displayLabel": "US Dollar ($)" + }, + "interestRate": 9.85, + "interestRatePeriodFrequencyType": { + "id": 3, + "code": "savings.interest.rate.periodFrequencyType.years", + "value": "Per year" + }, + "minRequiredOpeningBalance": 1000, + "lockinPeriodFrequency": 3, + "lockinPeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + } + } +] + +
+
+ + + +   +
+
+

Savings Account:

+

An instance of a savings account for a individual or group.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Field Descriptions
clientId
The client you are creating the savings account for. Either clientId or groupId must be provided.
groupId
The group you are creating the savings account for. Either clientId or groupId must be provided.
productId
The id of the product used for this savings account. The savings account inherits the selected currency of the product and possibly other details if not overridden in the savings account creation request.
accountNo
The account no. associated with this loan. Is auto generated if not provided at creation time.
externalId
A place to put an external reference for this savings account e.g. The ID another system uses. If provided, it must be unique.
interestRate
The default interest rate set when creating savings accounts of this type of product. e.g. 5% Per year
interestRatePeriodFrequencyType
The default interest rate period type. 2=Per month, 3=Per year e.g. 5% Per year
minRequiredOpeningBalance
Optional: If provided, sets the minimum deposit amount required to open a savings account e.g. 2,000
lockinPeriodFrequency
Optional: If provided, used along with lockinPeriodFrequencyType to indicate the length of time that the savings account is 'locked in' and withdrawals are not allowed. e.g. 6 Months
lockinPeriodFrequencyType
Optional: If provided, used along with lockinPeriodFrequency to indicate the length of time that the savings account is 'locked in' and withdrawals are not allowed. 0=Days, 1=Weeks, 2=Months, 3=Years + e.g. 6 Months
+
+
+ +   +
+
+

Retrieve Savings Account Template:

+

This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of: +

    +
  • Field Defaults
  • +
  • Allowed Value Lists
  • +
+

+

Arguments

+
+
clientId
+
Integer mandatory
+
productId
+
Integer optional
+
If entered, productId, productName and selectedProduct fields are returned.
+
+

Example Requests:

+
savingsaccounts/template?clientId=1
+

+
savingsaccounts/template?clientId=1&productId=1
+
+
+ GET https://Domain Name/api/v1/savingsaccounts/template?clientId={clientId} + +{ + "clientId": 1, + "clientName": "Client A AB", + "productOptions": [ + { + "id": 1, + "name": "First" + } + ] +} + +
+ +
+ GET https://Domain Name/api/v1/savingsaccounts/template?clientId={clientId}&productId={productId} + +{ + "clientId": 1, + "clientName": "Client A AB", + "savingsProductId": 1, + "savingsProductName": "First", + "currency": { + "code": "USD", + "name": "US Dollar", + "decimalPlaces": 2, + "displaySymbol": "$", + "nameCode": "currency.USD", + "displayLabel": "US Dollar ($)" + }, + "interestRate": 12, + "interestRatePeriodFrequencyType": { + "id": 3, + "code": "savings.interest.rate.periodFrequencyType.years", + "value": "Per year" + }, + "minRequiredOpeningBalance": 1000, + "lockinPeriodFrequency": 3, + "lockinPeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + }, + "productOptions": [ + { + "id": 1, + "name": "First" + } + ], + "interestRatePeriodFrequencyTypeOptions": [ + { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + }, + { + "id": 3, + "code": "savings.interest.rate.periodFrequencyType.years", + "value": "Per year" + } + ], + "lockinPeriodFrequencyTypeOptions": [ + { + "id": 0, + "code": "savings.lockin.periodFrequencyType.days", + "value": "Days" + }, + { + "id": 1, + "code": "savings.lockin.periodFrequencyType.weeks", + "value": "Weeks" + }, + { + "id": 2, + "code": "savings.lockin.periodFrequencyType.months", + "value": "Months" + }, + { + "id": 3, + "code": "savings.lockin.periodFrequencyType.years", + "value": "Years" + } + ] +} + +
+
+ +   +
+
+

Create a New Savings Account

+
+ + + +
Mandatory Fields
clientId or groupId, productId, accountNo, externalId
+
+ + + +
Optional Fields
accountNo, externalId
+
+ + + +
Inherited from Product (if not provided)
interestRate, interestRatePeriodFrequencyType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType
+
+
+

Minimal request: accountNo auto generated, remaining details inherited from savings product.

+ POST https://Domain Name/api/v1/savingsaccounts + POST savingaccount +Content-Type: application/json +Request Body: +{ + "clientId": 1, + "productId": 1 +} + +

Minimal request: accountNo provided (must be unique), remaining details inherited from savings product.

+ POST savingaccount +Content-Type: application/json +Request Body: +{ + "clientId": 1, + "productId": 1, + "accountNo": "SA000023", + "externalId": "SYS-23" +} + +

Full request: accountNo provided (must be unique), remaining details override details from savings product (except currency).

+ POST savingaccount +Content-Type: application/json +Request Body: +{ + "clientId": 1, + "productId": 1, + "accountNo": "SA000023", + "externalId": "SYS-23", + "locale": "en", + "interestRate": "5.65", + "interestRatePeriodFrequencyType": 2, + "minRequiredOpeningBalance": "1,000", + "lockinPeriodFrequency": 6, + "lockinPeriodFrequencyType": 2 +} + + +{ + "officeId": 1, + "clientId": 1, + "resourceId": 1 +} + +
+
+ +   +
+
+

List Savings Accounts

+

Example Requests:

+
savingsaccounts
+

+
savingsaccounts?fields=name
+
+
+ GET https://Domain Name/api/v1/savingsaccounts + +[ + { + "id": 1, + "accountNo": "SA000023", + "externalId": "SYS-23", + "groupId": 0, + "clientId": 1, + "clientName": "Client A AB", + "savingsProductId": 1, + "savingsProductName": "First", + "currency": { + "code": "USD", + "name": "US Dollar", + "decimalPlaces": 2, + "displaySymbol": "$", + "nameCode": "currency.USD", + "displayLabel": "US Dollar ($)" + }, + "interestRate": 5.65, + "interestRatePeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + }, + "annualInterestRate": 67.8, + "minRequiredOpeningBalance": 1000, + "lockinPeriodFrequency": 6, + "lockinPeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + } + } +] + +
+
+ +   +
+
+

Retrieve a Savings Account:

+

Arguments

+
+
associations
+
optional, Either 'all' or a comma separated list of savings 'associations' (itemised below).
+

Associations are just extra pieces of data that you might or might not want to retrieve.

+
'all': Gets data related to all associations e.g. ?associations=all.
+
'transactions': Gets data related to transactions on the account e.g. ?associations=transactions
+
+

Example Requests :

+
savingsaccounts/1
+

+
savingsaccounts/1?associations=all
+
+
+ GET https://DomainName/api/v1/savingsaccounts/{accountId} + +{ + "id": 1, + "accountNo": "SA000023", + "externalId": "SYS-23", + "groupId": 0, + "clientId": 1, + "clientName": "Client A AB", + "savingsProductId": 1, + "savingsProductName": "First", + "currency": { + "code": "USD", + "name": "US Dollar", + "decimalPlaces": 2, + "displaySymbol": "$", + "nameCode": "currency.USD", + "displayLabel": "US Dollar ($)" + }, + "interestRate": 5.65, + "interestRatePeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + }, + "annualInterestRate": 67.8, + "minRequiredOpeningBalance": 1000, + "lockinPeriodFrequency": 6, + "lockinPeriodFrequencyType": { + "id": 2, + "code": "savings.interest.rate.periodFrequencyType.months", + "value": "Per month" + } +} + +
+
+ +   +
+
+

Update a Savings Account

+

Will most likely have a restriction to only allow 'inactive' savings accounts to be updated.

+

As other updates like change of interest rate are possibly special cases for savings.

+
+
+ PUT https://Domain Name/api/v1/savingsaccounts/{accountsId} + PUT savingsaccounts/1 +Content-Type: application/json +No Request Body: +{ + "locale": "en", + "interestRate": "5.2323" +} + + +{ + "officeId": 1, + "clientId": 1, + "resourceId": 1, + "changes": { + "interestRate": 5.2323, + "locale": "en" + } +} + +
+
+ +   +
+
+

Delete a Savings Account

+

At present we support hard delete of savings account but this is likely to change to a savings account closure or de-activation process/command.

+
+
+ DELETE https://Domain Name/api/v1/savingsaccounts/{accountsId} + DELETE savingsaccounts/1 +Content-Type: application/json +No Request Body: + + +{ + "officeId": 1, + "clientId": 1, + "resourceId": 1 +} + +
+
+ + +  
@@ -9252,9 +7956,7 @@ Request Body:
Group
- Deposit Account -
- Saving Account + Savings Account @@ -12421,6 +11123,23 @@ Content-Type: application/json + + Loan Product + loanproducts + Create a Loan Product + List Loan Products + + + + + + loanproducts/{productId} + + Retrieve a Loan + Product + Update a Loan Product + + Loans loans?calculateLoanSchedule @@ -12560,7 +11279,39 @@ Content-Type: application/json Delete a Guarantor - OFFICE + Savings Product + savingsproducts + Create a Savings product + List Savings products + + + + + + savingsproducts/{productId} + + Retrieve a Savings product + Update a Savings product + Delete a Savings product + + + Savings Accounts + savingsaccounts + Create new Savings Account + List Savings Accounts + + + + + + savingsaccounts/{accountId} + + Retrieve a Savings Account + Update a Savings Account + Delete a Savings Account + + + Office offices Create an Office List Offices @@ -12575,23 +11326,7 @@ Content-Type: application/json Update an Office - - LOAN PRODUCT - loanproducts - Create a Loan Product - List Loan Products - - - - - - loanproducts/{productId} - - Retrieve a Loan - Product - Update a Loan Product - - + CURRENCY currencies @@ -12908,87 +11643,10 @@ Content-Type: application/json PERMISSION permissions - List Application - Permissions + List Permissions - - - DEPOSIT PRODUCT - depositproducts - Create a Deposit product - List Deposit products - - - - - - depositproducts/{prodcutId} - - Retrieve a Deposit product - Update a Deposit product - Delete a Deposit product - - - SAVING PRODUCT - savingproducts - Create a Saving product - List Saving products - - - - - - savingproducts/{prodcutId} - - Retrieve a Saving procduct - Update a Saving product - Delete a Saving product - - - - FIXED DEPOSITS - depositaccounts - Create a New Deposit - Application - - - - - - - depositaccounts/{accountId} - Approve, Undo Approve, - Interest withdraw, Reject a Deposit Application or Withdraw a - Deposit Application - Retrieve a Deposit - Application - - Delete a Deposit - Application - - - - SAVING ACCOUNTS - savingaccounts - Create a New Saving - Application - - - - - - - savingaccounts/{accountId} - Approve, Undo Approve, - Interest withdraw, Reject a Saving Application or Withdraw a - Saving Application - Retrieve a Saving - Application - - Delete a Saving - Application - +
@@ -13011,35 +11669,39 @@ Content-Type: application/json - + + + + + - + - - - + + + - - + + + + + + - + - +
clients/templateRetrieve Client Details TemplateRetrieve Client Template
loanproducts/templateRetrieve Loan Product Template
loans/template?clientId={clientId}Retrieve Loan Details TemplateRetrieve Loan Template
loans/{loanId}/transactions/template Retrieve Tranaction Template
offices/templateRetrieve Office Details - Template
savingproducts/templateRetrieve Savings Product Template
loanproducts/templateRetrieve Loan Product - Details Templatesavingsaccounts/template?clientId={clientId}Retrieve Savings Account Template
offices/templateRetrieve Office Template
users/templateRetrieve User Details - TemplateRetrieve User Template
audit/searchtemplateRetrieve Audit Search - DataRetrieve Audit Search Template
diff --git a/mifosng-db/patches/3-drop-hugo-savings-schema-replace-with-basic-savings-schema.sql b/mifosng-db/patches/3-drop-hugo-savings-schema-replace-with-basic-savings-schema.sql new file mode 100644 index 000000000..06b9d43eb --- /dev/null +++ b/mifosng-db/patches/3-drop-hugo-savings-schema-replace-with-basic-savings-schema.sql @@ -0,0 +1,66 @@ +ALTER TABLE `mifostenant-default`.`m_note` +DROP FOREIGN KEY `FK_m_note_m_saving_account`, +DROP FOREIGN KEY `FK_m_note_m_deposit_account`; + +ALTER TABLE `mifostenant-default`.`m_note` +DROP COLUMN `saving_account_id`, +DROP COLUMN `deposit_account_id`, +DROP INDEX `FK_m_note_m_saving_account`, +DROP INDEX `FK_m_note_m_deposit_account`; + + +drop table `mifostenant-default`.`m_saving_account_transaction`; +drop table `mifostenant-default`.`m_saving_schedule`; +drop table `mifostenant-default`.`m_saving_account`; + +drop table `mifostenant-default`.`m_deposit_account_transaction`; +drop table `mifostenant-default`.`m_deposit_account`; + +drop table `mifostenant-default`.`m_product_savings`; +drop table `mifostenant-default`.`m_product_deposit`; + + + +DROP TABLE IF EXISTS `m_savings_account`; +DROP TABLE IF EXISTS `m_savings_product`; + +CREATE TABLE `m_savings_product` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `description` varchar(500) NOT NULL, + `currency_code` varchar(3) NOT NULL, + `currency_digits` smallint(5) NOT NULL, + `nominal_interest_rate_per_period` decimal(19,6) NOT NULL, + `nominal_interest_rate_period_frequency_enum` smallint(5) NOT NULL, + `min_required_opening_balance` decimal(19,6) DEFAULT NULL, + `lockin_period_frequency` decimal(19,6) DEFAULT NULL, + `lockin_period_frequency_enum` smallint(5) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `sp_unq_name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `m_savings_account` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `account_no` varchar(20) NOT NULL, + `external_id` varchar(100) DEFAULT NULL, + `client_id` bigint(20) DEFAULT NULL, + `group_id` bigint(20) DEFAULT NULL, + `product_id` bigint(20) DEFAULT NULL, + `currency_code` varchar(3) NOT NULL, + `currency_digits` smallint(5) NOT NULL, + `nominal_interest_rate_per_period` decimal(19,6) NOT NULL, + `nominal_interest_rate_period_frequency_enum` smallint(5) NOT NULL, + `annual_nominal_interest_rate` decimal(19,6) NOT NULL, + `min_required_opening_balance` decimal(19,6) DEFAULT NULL, + `lockin_period_frequency` decimal(19,6) DEFAULT NULL, + `lockin_period_frequency_enum` smallint(5) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `sa_account_no_UNIQUE` (`account_no`), + UNIQUE KEY `sa_externalid_UNIQUE` (`external_id`), + KEY `FKSA00000000000001` (`client_id`), + KEY `FKSA00000000000002` (`group_id`), + KEY `FKSA00000000000003` (`product_id`), + CONSTRAINT `FKSA00000000000001` FOREIGN KEY (`client_id`) REFERENCES `m_client` (`id`), + CONSTRAINT `FKSA00000000000002` FOREIGN KEY (`group_id`) REFERENCES `m_group` (`id`), + CONSTRAINT `FKSA00000000000003` FOREIGN KEY (`product_id`) REFERENCES `m_savings_product` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java index c2b1e1ce6..7979cef59 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java @@ -27,7 +27,8 @@ public class CommandWrapperBuilder { public CommandWrapper build() { return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.actionName, this.entityName, this.entityId, - this.apptableId, this.datatableId, this.codeId, this.supportedEntityType, this.supportedEntityId, this.href, this.json, this.transactionId); + this.apptableId, this.datatableId, this.codeId, this.supportedEntityType, this.supportedEntityId, this.href, this.json, + this.transactionId); } // public CommandWrapperBuilder withEntityId(final Long withId) { @@ -372,7 +373,7 @@ public class CommandWrapperBuilder { return this; } - public CommandWrapperBuilder updateLoanCharge(final Long loanId, Long loanChargeId) { + public CommandWrapperBuilder updateLoanCharge(final Long loanId, final Long loanChargeId) { this.actionName = "UPDATE"; this.entityName = "LOANCHARGE"; this.entityId = loanChargeId; @@ -568,7 +569,7 @@ public class CommandWrapperBuilder { return this; } - public CommandWrapperBuilder updateCodeValue(Long codeId, final Long codeValueId) { + public CommandWrapperBuilder updateCodeValue(final Long codeId, final Long codeValueId) { this.actionName = "UPDATE"; this.entityName = "CODEVALUE"; this.entityId = codeValueId; @@ -633,7 +634,7 @@ public class CommandWrapperBuilder { this.href = "/glaccounts/" + glAccountId; return this; } - + public CommandWrapperBuilder createJournalEntry() { this.actionName = "CREATE"; this.entityName = "JOURNALENTRY"; @@ -641,16 +642,16 @@ public class CommandWrapperBuilder { this.href = "/journalentries/template"; return this; } - + public CommandWrapperBuilder reverseJournalEntry(final String transactionId) { this.actionName = "REVERSE"; this.entityName = "JOURNALENTRY"; this.entityId = null; this.transactionId = transactionId; - this.href = "/journalentries/"+transactionId; + this.href = "/journalentries/" + transactionId; return this; } - + public CommandWrapperBuilder createDepositProduct() { this.actionName = "CREATE"; this.entityName = "DEPOSITPRODUCT"; @@ -659,198 +660,166 @@ public class CommandWrapperBuilder { return this; } - public CommandWrapperBuilder updateDepositProduct(final Long productId) { - this.actionName = "UPDATE"; + public CommandWrapperBuilder updateDepositProduct(final Long productId) { + this.actionName = "UPDATE"; this.entityName = "DEPOSITPRODUCT"; this.entityId = productId; - this.href = "/depositproducts/"+productId; + this.href = "/depositproducts/" + productId; return this; - } - - public CommandWrapperBuilder deleteDepositProduct(final Long productId) { - this.actionName = "DELETE"; - this.entityName = "DEPOSITPRODUCT"; - this.entityId = productId; - this.href = "/depositproducts/"+productId; - return this; - } + } - public CommandWrapperBuilder createDepositAccount() { - this.actionName = "CREATE"; + public CommandWrapperBuilder deleteDepositProduct(final Long productId) { + this.actionName = "DELETE"; + this.entityName = "DEPOSITPRODUCT"; + this.entityId = productId; + this.href = "/depositproducts/" + productId; + return this; + } + + public CommandWrapperBuilder createDepositAccount() { + this.actionName = "CREATE"; this.entityName = "DEPOSITACCOUNT"; this.entityId = null; this.href = "/depositaccounts/template"; return this; - } + } - public CommandWrapperBuilder updateDepositAccount(Long accountId) { - this.actionName = "UPDATE"; + public CommandWrapperBuilder updateDepositAccount(final Long accountId) { + this.actionName = "UPDATE"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder deleteDepositAccount(Long accountId) { - this.actionName = "DELETE"; + public CommandWrapperBuilder deleteDepositAccount(final Long accountId) { + this.actionName = "DELETE"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder approveDepositApplication(Long accountId) { - this.actionName = "APPROVE"; + public CommandWrapperBuilder approveDepositApplication(final Long accountId) { + this.actionName = "APPROVE"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder withdrawDepositAmount(Long accountId) { - this.actionName = "WITHDRAWAL"; + public CommandWrapperBuilder withdrawDepositAmount(final Long accountId) { + this.actionName = "WITHDRAWAL"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder withdrawInterestDepositAmount(Long accountId) { - this.actionName = "INTEREST"; + public CommandWrapperBuilder withdrawInterestDepositAmount(final Long accountId) { + this.actionName = "INTEREST"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder renewDepositAccount(Long accountId) { - this.actionName = "RENEW"; + public CommandWrapperBuilder renewDepositAccount(final Long accountId) { + this.actionName = "RENEW"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder rejectDepositAccount(Long accountId) { - this.actionName = "REJECT"; + public CommandWrapperBuilder rejectDepositAccount(final Long accountId) { + this.actionName = "REJECT"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder withdrawDepositApplication(Long accountId) { - this.actionName = "WITHDRAW"; + public CommandWrapperBuilder withdrawDepositApplication(final Long accountId) { + this.actionName = "WITHDRAW"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder undoDepositApplicationApproval(Long accountId) { - this.actionName = "APPROVALUNDO"; + public CommandWrapperBuilder undoDepositApplicationApproval(final Long accountId) { + this.actionName = "APPROVALUNDO"; this.entityName = "DEPOSITACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/depositaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder createSavingProduct() { - this.actionName = "CREATE"; + public CommandWrapperBuilder createSavingProduct() { + this.actionName = "CREATE"; this.entityName = "SAVINGSPRODUCT"; this.entityId = null; - this.href = "/savingproducts/template"; + this.href = "/savingsproducts/template"; return this; - } + } - public CommandWrapperBuilder updateSavingProduct(Long productId) { - this.actionName = "UPDATE"; + public CommandWrapperBuilder updateSavingProduct(final Long productId) { + this.actionName = "UPDATE"; this.entityName = "SAVINGSPRODUCT"; this.entityId = productId; - this.href = "/savingproducts/"+productId; + this.href = "/savingsproducts/" + productId; return this; - } + } - public CommandWrapperBuilder deleteSavingProduct(Long productId) { - this.actionName = "DELETE"; + public CommandWrapperBuilder deleteSavingProduct(final Long productId) { + this.actionName = "DELETE"; this.entityName = "SAVINGSPRODUCT"; this.entityId = productId; - this.href = "/savingproducts/"+productId; + this.href = "/savingsproducts/" + productId; return this; - } + } - public CommandWrapperBuilder createSavingAccount() { - this.actionName = "CREATE"; + public CommandWrapperBuilder createSavingsAccount() { + this.actionName = "CREATE"; this.entityName = "SAVINGSACCOUNT"; this.entityId = null; - this.href = "/savingaccounts/template"; + this.href = "/savingsaccounts/template"; return this; - } + } - public CommandWrapperBuilder updateSavingAccount(Long accountId) { - this.actionName = "UPDATE"; + public CommandWrapperBuilder updateSavingsAccount(final Long accountId) { + this.actionName = "UPDATE"; this.entityName = "SAVINGSACCOUNT"; this.entityId = accountId; - this.href = "/savingproducts/"+accountId; + this.href = "/savingsaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder deleteSavingAccount(Long accountId) { - this.actionName = "DELETE"; + public CommandWrapperBuilder deleteSavingsAccount(final Long accountId) { + this.actionName = "DELETE"; this.entityName = "SAVINGSACCOUNT"; this.entityId = accountId; - this.href = "/savingproducts/"+accountId; + this.href = "/savingsaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder approveSavingAccountApplication(Long accountId) { - this.actionName = "APPROVE"; + public CommandWrapperBuilder depositOfSavingAmount(final Long accountId) { + this.actionName = "DEPOSIT"; this.entityName = "SAVINGSACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/savingsaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder depositOfSavingAmount(Long accountId) { - this.actionName = "DEPOSIT"; + public CommandWrapperBuilder withdrawSavingAmount(final Long accountId) { + this.actionName = "WITHDRAWAL"; this.entityName = "SAVINGSACCOUNT"; this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; + this.href = "/savingsaccounts/" + accountId; return this; - } + } - public CommandWrapperBuilder withdrawSavingAmount(Long accountId) { - this.actionName = "WITHDRAWAL"; - this.entityName = "SAVINGSACCOUNT"; - this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; - return this; - } - - public CommandWrapperBuilder rejectSavingApplication(Long accountId) { - this.actionName = "REJECT"; - this.entityName = "SAVINGSACCOUNT"; - this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; - return this; - } - - public CommandWrapperBuilder withdrawSavingApplication(Long accountId) { - this.actionName = "WITHDRAW"; - this.entityName = "SAVINGSACCOUNT"; - this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; - return this; - } - - public CommandWrapperBuilder undoApprovalOfSavingApplication(Long accountId) { - this.actionName = "APPROVALUNDO"; - this.entityName = "SAVINGSACCOUNT"; - this.entityId = accountId; - this.href = "/depositaccounts/"+accountId; - return this; - } - public CommandWrapperBuilder createCalendar(final String supportedEntityType, final Long supportedEntityId) { this.actionName = "CREATE"; this.entityName = "CALENDAR"; @@ -875,10 +844,11 @@ public class CommandWrapperBuilder { this.href = "/" + supportedEntityType + "/" + supportedEntityId + "/calendars/" + calendarId; return this; } - + public CommandWrapperBuilder createNote(final String entityName, final String resourceType, final Long resourceId) { this.actionName = "CREATE"; - this.entityName = entityName;//Note supports multiple resources. Note Permissions are set for each resource. + this.entityName = entityName;// Note supports multiple resources. Note + // Permissions are set for each resource. this.supportedEntityType = resourceType; this.supportedEntityId = resourceId; this.href = "/" + resourceType + "/" + resourceId + "/notes/template"; @@ -887,7 +857,8 @@ public class CommandWrapperBuilder { public CommandWrapperBuilder updateNote(final String entityName, final String resourceType, final Long resourceId, final Long noteId) { this.actionName = "UPDATE"; - this.entityName = entityName;//Note supports multiple resources. Note Permissions are set for each resource. + this.entityName = entityName;// Note supports multiple resources. Note + // Permissions are set for each resource. this.entityId = noteId; this.supportedEntityType = resourceType; this.supportedEntityId = resourceId; @@ -897,21 +868,22 @@ public class CommandWrapperBuilder { public CommandWrapperBuilder deleteNote(final String entityName, final String resourceType, final Long resourceId, final Long noteId) { this.actionName = "DELETE"; - this.entityName = entityName;//Note supports multiple resources. Note Permissions are set for each resource. + this.entityName = entityName;// Note supports multiple resources. Note + // Permissions are set for each resource. this.entityId = noteId; this.supportedEntityType = resourceType; this.supportedEntityId = resourceId; this.href = "/" + resourceType + "/" + resourceId + "/calendars/" + noteId; return this; } - + public CommandWrapperBuilder createGroup() { this.actionName = "CREATE"; this.entityName = "GROUP"; this.href = "/groups/template"; return this; } - + public CommandWrapperBuilder updateGroup(final Long groupId) { this.actionName = "UPDATE"; this.entityName = "GROUP"; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java index dc539f5cb..1f5af54a9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java @@ -375,33 +375,21 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer } } else if (wrapper.isSavingProductResource()) { if (wrapper.isCreate()) { - handler = applicationContext.getBean("createSavingProductCommandHandler", NewCommandSourceHandler.class); + handler = applicationContext.getBean("createSavingsProductCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isUpdate()) { - handler = applicationContext.getBean("updateSavingProductCommandHandler", NewCommandSourceHandler.class); + handler = applicationContext.getBean("updateSavingsProductCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isDelete()) { - handler = applicationContext.getBean("deleteSavingProductCommandHandler", NewCommandSourceHandler.class); + handler = applicationContext.getBean("deleteSavingsProductCommandHandler", NewCommandSourceHandler.class); } else { throw new UnsupportedCommandException(wrapper.commandName()); } } else if (wrapper.isSavingAccountResource()) { if (wrapper.isCreate()) { - handler = applicationContext.getBean("createSavingAccountCommandHandler", NewCommandSourceHandler.class); + handler = applicationContext.getBean("createSavingsAccountCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isUpdate()) { - handler = applicationContext.getBean("updateSavingAccountCommandHandler", NewCommandSourceHandler.class); + handler = applicationContext.getBean("updateSavingsAccountCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isDelete()) { - handler = applicationContext.getBean("deleteSavingAccountCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isApprovalOfSaving()) { - handler = applicationContext.getBean("approveSavingAccountCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isSavingAccountDeposit()) { - handler = applicationContext.getBean("depositSavingAmountCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isRejectOfSavingAccount()) { - handler = applicationContext.getBean("rejectSavingAccountCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isWithdrawSavingAmount()) { - handler = applicationContext.getBean("withdrawSavingAmountCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isWithdrawOfSavingApplicatin()) { - handler = applicationContext.getBean("withdrawSavingApplicationCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isUndoApprovalOfSavingAccount()) { - handler = applicationContext.getBean("undoApprovalSavingAccountCommandHandler", NewCommandSourceHandler.class); + handler = applicationContext.getBean("deleteSavingsAccountCommandHandler", NewCommandSourceHandler.class); } else { throw new UnsupportedCommandException(wrapper.commandName()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java index 11d618210..0261af630 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java @@ -42,6 +42,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.jdbc.support.rowset.SqlRowSetMetaData; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import com.google.gson.reflect.TypeToken; @@ -103,6 +104,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ logger.error(dve.getMessage(), dve); } + @Transactional @Override public void registerDatatable(final String dataTableName, final String applicationTableName) { @@ -176,6 +178,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } + @Transactional @Override public void deregisterDatatable(final String datatable) { final String permissionList = "('CREATE_" + datatable + "', 'CREATE_" + datatable + "_CHECKER', 'READ_" + datatable + "', 'UPDATE_" @@ -192,6 +195,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ this.jdbcTemplate.batchUpdate(sqlArray); } + @Transactional @Override public void createNewDatatableEntry(final String dataTableName, final Long appTableId, final JsonCommand command) { @@ -230,6 +234,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } + @Transactional @Override public Map updateDatatableEntryOneToOne(final String datatable, final Long appTableId, final JsonCommand command) { @@ -258,6 +263,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return changes; } + @Transactional @Override public Map updateDatatableEntryOneToMany(final String datatable, final Long appTableId, final Long datatableId, final JsonCommand command) { @@ -284,6 +290,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return changes; } + @Transactional @Override public void deleteDatatableEntries(final String datatable, final Long appTableId) { @@ -295,6 +302,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (rowsDeleted < 1) { throw new DatatableNotFoundException(datatable, appTableId); } } + @Transactional @Override public void deleteDatatableEntry(final String datatable, final Long appTableId, final Long datatableId) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGeneratorFactory.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGeneratorFactory.java index e00094c44..d73ca7923 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGeneratorFactory.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGeneratorFactory.java @@ -17,4 +17,8 @@ public class AccountNumberGeneratorFactory { public AccountNumberGenerator determineLoanAccountNoGenerator(final Long loanId) { return new ZeroPaddedAccountNumberGenerator(loanId, 9); } + + public AccountNumberGenerator determineSavingsAccountNoGenerator(final Long savingsAccountId) { + return new ZeroPaddedAccountNumberGenerator(savingsAccountId, 9); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java index 29e676db1..3f7f59cae 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java @@ -37,7 +37,7 @@ import org.mifosplatform.portfolio.group.domain.Group; import org.springframework.data.jpa.domain.AbstractPersistable; @Entity -@Table(name = "m_client", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_no" }, name = "account_no_UNIQUE")}) +@Table(name = "m_client", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_no" }, name = "account_no_UNIQUE") }) public class Client extends AbstractPersistable { @Column(name = "account_no", length = 20, unique = true, nullable = false) @@ -79,11 +79,11 @@ public class Client extends AbstractPersistable { @ManyToMany @JoinTable(name = "m_group_client", joinColumns = @JoinColumn(name = "client_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) private Set parentGroups; - + @Transient private boolean accountNumberRequiresAutoGeneration = false; - public static Client fromJson(final Office clientOffice, final Group clientParentGroup , final JsonCommand command) { + public static Client fromJson(final Office clientOffice, final Group clientParentGroup, final JsonCommand command) { final String accountNo = command.stringValueOfParameterNamed("accountNo"); final String firstname = command.stringValueOfParameterNamed("firstname"); @@ -93,15 +93,15 @@ public class Client extends AbstractPersistable { final LocalDate joiningDate = command.localDateValueOfParameterNamed("joinedDate"); final String externalId = command.stringValueOfParameterNamed("externalId"); - return new Client(clientOffice, clientParentGroup ,accountNo, firstname, middlename, lastname, fullname, joiningDate, externalId); + return new Client(clientOffice, clientParentGroup, accountNo, firstname, middlename, lastname, fullname, joiningDate, externalId); } protected Client() { - + } - private Client(final Office office, final Group clientParentGroup, final String accountNo, final String firstname, final String middlename, final String lastname, - final String fullname, final LocalDate openingDate, final String externalId) { + private Client(final Office office, final Group clientParentGroup, final String accountNo, final String firstname, + final String middlename, final String lastname, final String fullname, final LocalDate openingDate, final String externalId) { if (StringUtils.isBlank(accountNo)) { this.accountNumber = new RandomPasswordGenerator(19).generate(); this.accountNumberRequiresAutoGeneration = true; @@ -139,11 +139,11 @@ public class Client extends AbstractPersistable { this.fullname = null; } - if(clientParentGroup != null){ + if (clientParentGroup != null) { this.parentGroups = new HashSet(); this.parentGroups.add(clientParentGroup); } - + deriveDisplayName(); validateNameParts(); } @@ -152,7 +152,7 @@ public class Client extends AbstractPersistable { return this.accountNumberRequiresAutoGeneration; } - public void setAccountNumberRequiresAutoGeneration(boolean accountNumberRequiresAutoGeneration) { + public void setAccountNumberRequiresAutoGeneration(final boolean accountNumberRequiresAutoGeneration) { this.accountNumberRequiresAutoGeneration = accountNumberRequiresAutoGeneration; } @@ -160,7 +160,7 @@ public class Client extends AbstractPersistable { return identifier.equalsIgnoreCase(this.externalId); } - public boolean identifiedBy(Long clientId) { + public boolean identifiedBy(final Long clientId) { return getId().equals(clientId); } @@ -346,7 +346,11 @@ public class Client extends AbstractPersistable { return imageKey; } - public void setImageKey(String imageKey) { + public void setImageKey(final String imageKey) { this.imageKey = imageKey; } + + public Long officeId() { + return this.office.getId(); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java index 884506537..b2d019f89 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java @@ -216,31 +216,35 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService List preclosedDepositAccounts = new ArrayList(); List maturedDepositAccounts = new ArrayList(); - ClientDespoitAccountSummaryDataMapper depositAccountMapper = new ClientDespoitAccountSummaryDataMapper(); - - String depositAccountsSql = "select " + depositAccountMapper.schema() + " where da.client_id = ? and da.is_deleted=0"; - List depositAccountResults = this.jdbcTemplate.query(depositAccountsSql, depositAccountMapper, - new Object[] { clientId }); - if (depositAccountResults != null) { - for (ClientAccountSummaryData row : depositAccountResults) { - - if (row.accountStatusId() == 100) { - pendingApprovalDepositAccounts.add(row); - } else if (row.accountStatusId() == 300) { - approvedDepositAccounts.add(row); - } else if (row.accountStatusId() == 400) { - withdrawnByClientDespositAccounts.add(row); - } else if (row.accountStatusId() == 500) { - rejectedDepositAccounts.add(row); - } else if (row.accountStatusId() == 600) { - closedDepositAccounts.add(row); - } else if (row.accountStatusId() == 700) { - maturedDepositAccounts.add(row); - } else if (row.accountStatusId() == 800) { - preclosedDepositAccounts.add(row); - } - } - } + // ClientDespoitAccountSummaryDataMapper depositAccountMapper = new + // ClientDespoitAccountSummaryDataMapper(); + // + // String depositAccountsSql = "select " + + // depositAccountMapper.schema() + + // " where da.client_id = ? and da.is_deleted=0"; + // List depositAccountResults = + // this.jdbcTemplate.query(depositAccountsSql, depositAccountMapper, + // new Object[] { clientId }); + // if (depositAccountResults != null) { + // for (ClientAccountSummaryData row : depositAccountResults) { + // + // if (row.accountStatusId() == 100) { + // pendingApprovalDepositAccounts.add(row); + // } else if (row.accountStatusId() == 300) { + // approvedDepositAccounts.add(row); + // } else if (row.accountStatusId() == 400) { + // withdrawnByClientDespositAccounts.add(row); + // } else if (row.accountStatusId() == 500) { + // rejectedDepositAccounts.add(row); + // } else if (row.accountStatusId() == 600) { + // closedDepositAccounts.add(row); + // } else if (row.accountStatusId() == 700) { + // maturedDepositAccounts.add(row); + // } else if (row.accountStatusId() == 800) { + // preclosedDepositAccounts.add(row); + // } + // } + // } List pendingApprovalSavingAccounts = new ArrayList(); List approvedSavingAccounts = new ArrayList(); @@ -248,25 +252,30 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService List rejectedSavingAccounts = new ArrayList(); List closedSavingAccounts = new ArrayList(); - ClientSavingAccountSummaryDataMapper clientSavingAccountSummaryDataMapper = new ClientSavingAccountSummaryDataMapper(); - String savingAccountsSql = "select " + clientSavingAccountSummaryDataMapper.schema() - + " where sa.client_id=? and sa.is_deleted=0"; - List savingAccountsResults = this.jdbcTemplate.query(savingAccountsSql, - clientSavingAccountSummaryDataMapper, new Object[] { clientId }); - - if (savingAccountsResults != null) { - for (ClientAccountSummaryData account : savingAccountsResults) { - if (account.accountStatusId() == 100) - pendingApprovalSavingAccounts.add(account); - else if (account.accountStatusId() == 300) - approvedSavingAccounts.add(account); - else if (account.accountStatusId() == 400) - withdrawnByClientSavingAccounts.add(account); - else if (account.accountStatusId() == 500) - rejectedSavingAccounts.add(account); - else if (account.accountStatusId() == 600) closedSavingAccounts.add(account); - } - } + // ClientSavingAccountSummaryDataMapper + // clientSavingAccountSummaryDataMapper = new + // ClientSavingAccountSummaryDataMapper(); + // String savingAccountsSql = "select " + + // clientSavingAccountSummaryDataMapper.schema() + // + " where sa.client_id=? and sa.is_deleted=0"; + // List savingAccountsResults = + // this.jdbcTemplate.query(savingAccountsSql, + // clientSavingAccountSummaryDataMapper, new Object[] { clientId }); + // + // if (savingAccountsResults != null) { + // for (ClientAccountSummaryData account : savingAccountsResults) { + // if (account.accountStatusId() == 100) + // pendingApprovalSavingAccounts.add(account); + // else if (account.accountStatusId() == 300) + // approvedSavingAccounts.add(account); + // else if (account.accountStatusId() == 400) + // withdrawnByClientSavingAccounts.add(account); + // else if (account.accountStatusId() == 500) + // rejectedSavingAccounts.add(account); + // else if (account.accountStatusId() == 600) + // closedSavingAccounts.add(account); + // } + // } return new ClientAccountSummaryCollectionData(pendingApprovalLoans, awaitingDisbursalLoans, openLoans, closedLoans, pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts, rejectedDepositAccounts, @@ -320,30 +329,6 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService } } - private static final class ClientDespoitAccountSummaryDataMapper implements RowMapper { - - public String schema() { - - StringBuilder accountsSummary = new StringBuilder("da.id as id, da.external_id as externalId,"); - accountsSummary.append("da.product_id as productId, dp.name as productName,").append("da.status_enum as statusId ") - .append("from m_deposit_account da ").append("LEFT JOIN m_product_deposit AS dp ON dp.id = da.product_id "); - - return accountsSummary.toString(); - } - - @Override - public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - Long id = JdbcSupport.getLong(rs, "id"); - String externalId = rs.getString("externalId"); - Long productId = JdbcSupport.getLong(rs, "productId"); - String productName = rs.getString("productName"); - Integer accountStatusId = JdbcSupport.getInteger(rs, "statusId"); - - return new ClientAccountSummaryData(id, externalId, productId, productName, accountStatusId); - } - } - @Override public ClientData retrieveClientByIdentifier(final Long identifierTypeId, final String identifierKey) { try { @@ -383,29 +368,4 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService return ClientData.clientIdentifier(id, accountNo, firstname, middlename, lastname, fullname, displayName, officeId, officeName); } } - - private static final class ClientSavingAccountSummaryDataMapper implements RowMapper { - - public String schema() { - - StringBuilder accountsSummary = new StringBuilder("sa.id as id, sa.external_id as externalId,"); - accountsSummary.append("sa.product_id as productId, sp.name as productName,").append("sa.status_enum as statusId ") - .append("from m_saving_account sa ").append("LEFT JOIN m_product_savings AS sp ON sp.id = sa.product_id "); - - return accountsSummary.toString(); - } - - @Override - public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - Long id = JdbcSupport.getLong(rs, "id"); - String externalId = rs.getString("externalId"); - Long productId = JdbcSupport.getLong(rs, "productId"); - String productName = rs.getString("productName"); - Integer accountStatusId = JdbcSupport.getInteger(rs, "statusId"); - - return new ClientAccountSummaryData(id, externalId, productId, productName, accountStatusId); - } - } - } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java index 947729131..8a4177ffb 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java @@ -215,4 +215,7 @@ public class Group extends AbstractPersistable { return this.office.identifiedBy(officeId); } -} + public Long officeId() { + return this.office.getId(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java index 58181e9af..5838507d4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java @@ -191,8 +191,6 @@ public class LoansApiResource { final boolean feeChargesOnly = false; chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); - // chargeTemplate = - // this.loanChargeReadPlatformService.retrieveLoanChargeTemplate(); } LoanAccountData newLoanAccount = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java index 61d288758..7f84811a6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java @@ -441,7 +441,7 @@ public class Loan extends AbstractPersistable { * @param suppliedTransactionDate * @return */ - private LoanTransaction getChargeAppliedTransaction(final LoanCharge loanCharge, LocalDate suppliedTransactionDate) { + private LoanTransaction getChargeAppliedTransaction(final LoanCharge loanCharge, final LocalDate suppliedTransactionDate) { final Money chargeAmount = loanCharge.getAmount(getCurrency()); Money feeCharges = chargeAmount; Money penaltyCharges = Money.zero(loanCurrency()); @@ -2165,9 +2165,9 @@ public class Loan extends AbstractPersistable { public Long getOfficeId() { Long officeId = null; if (this.client != null) { - officeId = this.client.getOffice().getId(); + officeId = this.client.officeId(); } else { - // officeId = this.group.getOffice().getId(); + officeId = this.group.officeId(); } return officeId; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AprCalculator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AprCalculator.java index 33a2e5031..1f7ec822c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AprCalculator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AprCalculator.java @@ -13,10 +13,11 @@ import org.springframework.stereotype.Component; @Component public class AprCalculator { - public BigDecimal calculateFrom(PeriodFrequencyType interestPeriodFrequencyType, BigDecimal interestRatePerPeriod) { + public BigDecimal calculateFrom(final PeriodFrequencyType interestPeriodFrequencyType, final BigDecimal interestRatePerPeriod) { BigDecimal defaultAnnualNominalInterestRate = BigDecimal.ZERO; switch (interestPeriodFrequencyType) { case DAYS: + defaultAnnualNominalInterestRate = interestRatePerPeriod.multiply(BigDecimal.valueOf(365)); break; case WEEKS: defaultAnnualNominalInterestRate = interestRatePerPeriod.multiply(BigDecimal.valueOf(52)); @@ -33,5 +34,4 @@ public class AprCalculator { return defaultAnnualNominalInterestRate; } - -} +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/api/NotesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/api/NotesApiResource.java index 4b58f51ba..5fabdf8ff 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/api/NotesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/api/NotesApiResource.java @@ -69,13 +69,14 @@ public class NotesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveNotesByResource(@PathParam("resourceType") final String resourceType, @PathParam("resourceId") final Long resourceId, @Context final UriInfo uriInfo) { - + NoteType noteType = NoteType.fromApiUrl(resourceType); - - if(noteType == null){ throw new NoteResourceNotSupportedException(resourceType); }; - + + if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); } + ; + this.context.authenticatedUser().validateHasReadPermission(getResourceNameForPermissions(noteType)); - + final Integer noteTypeId = noteType.getValue(); final Collection notes = this.readPlatformService.retrieveNotesByResource(resourceId, noteTypeId); @@ -92,9 +93,10 @@ public class NotesApiResource { @PathParam("noteId") final Long noteId, @Context final UriInfo uriInfo) { NoteType noteType = NoteType.fromApiUrl(resourceType); - - if(noteType == null){ throw new NoteResourceNotSupportedException(resourceType); }; - + + if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); } + ; + this.context.authenticatedUser().validateHasReadPermission(getResourceNameForPermissions(noteType)); final Integer noteTypeId = noteType.getValue(); @@ -112,9 +114,10 @@ public class NotesApiResource { final String apiRequestBodyAsJson) { NoteType noteType = NoteType.fromApiUrl(resourceType); - - if(noteType == null){ throw new NoteResourceNotSupportedException(resourceType); }; - + + if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); } + ; + final String resourceNameForPermissions = getResourceNameForPermissions(noteType); final CommandWrapper commandRequest = new CommandWrapperBuilder().createNote(resourceNameForPermissions, resourceType, resourceId) .withJson(apiRequestBodyAsJson).build(); @@ -130,20 +133,22 @@ public class NotesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String updateNote(@PathParam("resourceType") final String resourceType, @PathParam("resourceId") final Long resourceId, @PathParam("noteId") final Long noteId, final String apiRequestBodyAsJson) { - + NoteType noteType = NoteType.fromApiUrl(resourceType); - - if(noteType == null){ throw new NoteResourceNotSupportedException(resourceType); }; - + + if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); } + ; + final String resourceNameForPermissions = getResourceNameForPermissions(noteType); - - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateNote(resourceNameForPermissions, resourceType, resourceId, noteId).withJson(apiRequestBodyAsJson).build(); + + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .updateNote(resourceNameForPermissions, resourceType, resourceId, noteId).withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } - + @DELETE @Path("{noteId}") @Consumes({ MediaType.APPLICATION_JSON }) @@ -152,42 +157,41 @@ public class NotesApiResource { @PathParam("noteId") final Long noteId) { NoteType noteType = NoteType.fromApiUrl(resourceType); - - if(noteType == null){ throw new NoteResourceNotSupportedException(resourceType); }; - + + if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); } + ; + final String resourceNameForPermissions = getResourceNameForPermissions(noteType); - - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteNote(resourceNameForPermissions, resourceType, resourceId, noteId).build(); + + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteNote(resourceNameForPermissions, resourceType, resourceId, + noteId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } - - private String getResourceNameForPermissions(NoteType type){ + + private String getResourceNameForPermissions(final NoteType type) { String resourceNameForPermissions = "INVALIDNOTE"; - switch(type){ + switch (type) { case CLIENT: resourceNameForPermissions = "CLIENTNOTE"; - break; + break; case LOAN: resourceNameForPermissions = "LOANNOTE"; - break; + break; case LOAN_TRANSACTION: resourceNameForPermissions = "LOANTRANSACTIONNOTE"; - break; - case DEPOSIT: - resourceNameForPermissions = "DEPOSITNOTE"; - break; - case SAVING: + break; + case SAVING_ACCOUNT: resourceNameForPermissions = "SAVINGNOTE"; - break; + break; case GROUP: resourceNameForPermissions = "GROUPNOTE"; - break; - + break; + } - + return resourceNameForPermissions; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java index d7aa09835..6f6242e94 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java @@ -21,8 +21,6 @@ import org.mifosplatform.portfolio.client.domain.Client; import org.mifosplatform.portfolio.group.domain.Group; import org.mifosplatform.portfolio.loanaccount.domain.Loan; import org.mifosplatform.portfolio.loanaccount.domain.LoanTransaction; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccount; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccount; import org.mifosplatform.useradministration.domain.AppUser; @Entity @@ -55,15 +53,10 @@ public class Note extends AbstractAuditableCustom { @Column(name = "note_type_enum") private final Integer noteTypeId; - @SuppressWarnings("unused") - @ManyToOne - @JoinColumn(name = "deposit_account_id", nullable = true) - private DepositAccount depositAccount; - - @SuppressWarnings("unused") - @ManyToOne - @JoinColumn(name = "saving_account_id", nullable = true) - private SavingAccount savingAccount; + // @SuppressWarnings("unused") + // @ManyToOne + // @JoinColumn(name = "saving_account_id", nullable = true) + // private SavingAccount savingAccount; public static Note clientNoteFromJson(final Client client, final JsonCommand command) { final String note = command.stringValueOfParameterNamed("note"); @@ -83,13 +76,10 @@ public class Note extends AbstractAuditableCustom { return new Note(loan, loanTransaction, note); } - public static Note depositNote(final DepositAccount account, final String note) { - return new Note(account, note); - } - - public static Note savingNote(final SavingAccount account, final String note) { - return new Note(account, note); - } + // public static Note savingNote(final SavingAccount account, final String + // note) { + // return new Note(account, note); + // } private Note(final Client client, final String note) { this.client = client; @@ -128,19 +118,12 @@ public class Note extends AbstractAuditableCustom { this.noteTypeId = null; } - public Note(final DepositAccount account, final String note) { - this.depositAccount = account; - this.client = account.client(); - this.note = note; - this.noteTypeId = NoteType.DEPOSIT.getValue(); - } - - public Note(final SavingAccount account, final String note) { - this.savingAccount = account; - this.client = account.getClient(); - this.note = note; - this.noteTypeId = NoteType.SAVING.getValue(); - } + // public Note(final SavingAccount account, final String note) { + // this.savingAccount = account; + // this.client = account.getClient(); + // this.note = note; + // this.noteTypeId = NoteType.SAVING_ACCOUNT.getValue(); + // } public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap(7); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteRepository.java index 9066b45cc..e68bb16f9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteRepository.java @@ -24,7 +24,7 @@ public interface NoteRepository extends JpaRepository, JpaSpecificat Note findByLoanTransactionIdAndId(Long loanTransactionId, Long id); - Note findByDepositAccountIdAndId(Long depositAccountId, Long id); + // Note findByDepositAccountIdAndId(Long depositAccountId, Long id); - Note findBySavingAccountIdAndId(Long savingAccountId, Long id); + // Note findBySavingAccountIdAndId(Long savingAccountId, Long id); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteType.java index f7016669c..edbc3f558 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/NoteType.java @@ -5,9 +5,11 @@ import java.util.Map; public enum NoteType { - CLIENT(100, "noteType.client", "clients"), LOAN(200, "noteType.loan", "loans"), LOAN_TRANSACTION(300, "noteType.loan.transaction", - "loanTransactions"), DEPOSIT(400, "noteType.deposit", "deposits"), SAVING(500, "noteType.saving", "savings"), GROUP(600, - "noteType.group", "groups"); + CLIENT(100, "noteType.client", "clients"), // + LOAN(200, "noteType.loan", "loans"), // + LOAN_TRANSACTION(300, "noteType.loan.transaction", "loanTransactions"), // + SAVING_ACCOUNT(500, "noteType.saving", "savings"), // + GROUP(600, "noteType.group", "groups"); private Integer value; private String code; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteEnumerations.java index 5d05ff7a9..c53b17dde 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteEnumerations.java @@ -26,11 +26,8 @@ public class NoteEnumerations { case LOAN_TRANSACTION: optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), "Loan transaction note"); break; - case DEPOSIT: - optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), "Deposit transaction note"); - break; - case SAVING: - optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), "Saving transaction note"); + case SAVING_ACCOUNT: + optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), "Saving account note"); break; case GROUP: optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), "Group note"); @@ -41,5 +38,5 @@ public class NoteEnumerations { } return optionData; } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java index ffedcf599..82d415f4e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java @@ -31,8 +31,8 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { private static final class NoteMapper implements RowMapper { public String schema() { - return " select n.id as id, n.client_id as clientId, n.group_id as groupId, n.loan_id as loanId, n.loan_transaction_id as transactionId, n.deposit_account_id as depositAccountId, " - + " n.saving_account_id as savingAccountId, n.note_type_enum as noteTypeEnum, n.note as note, n.created_date as createdDate, n.createdby_id as createdById, " + return " select n.id as id, n.client_id as clientId, n.group_id as groupId, n.loan_id as loanId, n.loan_transaction_id as transactionId, " + + " n.note_type_enum as noteTypeEnum, n.note as note, n.created_date as createdDate, n.createdby_id as createdById, " + " cb.username as createdBy, n.lastmodified_date as lastModifiedDate, n.lastmodifiedby_id as lastModifiedById, mb.username as modifiedBy " + " from m_note n left join m_appuser cb on cb.id=n.createdby_id left join m_appuser mb on mb.id=n.lastmodifiedby_id "; } @@ -45,8 +45,10 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { final Long groupId = JdbcSupport.getLong(rs, "groupId"); final Long loanId = JdbcSupport.getLong(rs, "loanId"); final Long transactionId = JdbcSupport.getLong(rs, "transactionId"); - final Long depositAccountId = JdbcSupport.getLong(rs, "depositAccountId"); - final Long savingAccountId = JdbcSupport.getLong(rs, "savingAccountId"); + // final Long depositAccountId = JdbcSupport.getLong(rs, + // "depositAccountId"); + // final Long savingAccountId = JdbcSupport.getLong(rs, + // "savingAccountId"); final Integer noteTypeId = JdbcSupport.getInteger(rs, "noteTypeEnum"); final EnumOptionData noteType = NoteEnumerations.noteType(noteTypeId); final String note = rs.getString("note"); @@ -56,7 +58,7 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { final Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById"); final String createdByUsername = rs.getString("createdBy"); final String updatedByUsername = rs.getString("modifiedBy"); - return new NoteData(id, clientId, groupId, loanId, transactionId, depositAccountId, savingAccountId, noteType, note, + return new NoteData(id, clientId, groupId, loanId, transactionId, null, null, noteType, note, createdDate, createdById, createdByUsername, lastModifiedDate, lastModifiedById, updatedByUsername); } } @@ -84,7 +86,7 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { final NoteType noteType = NoteType.fromInt(noteTypeId); final NoteMapper rm = new NoteMapper(); String conditionSql = getResourceCondition(noteType); - + final String sql = rm.schema() + " where " + conditionSql + " order by n.created_date DESC"; return this.jdbcTemplate.query(sql, rm, new Object[] { resourceId }); @@ -102,10 +104,7 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { case LOAN_TRANSACTION: conditionSql = " n.loan_transaction_id = ? "; break; - case DEPOSIT: - conditionSql = " n.deposit_account_id = ? "; - break; - case SAVING: + case SAVING_ACCOUNT: conditionSql = " n.saving_account_id = ? "; break; case GROUP: diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java index eb3d4e13d..448d3a133 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java @@ -28,12 +28,6 @@ import org.mifosplatform.portfolio.note.domain.NoteType; import org.mifosplatform.portfolio.note.exception.NoteNotFoundException; import org.mifosplatform.portfolio.note.exception.NoteResourceNotSupportedException; import org.mifosplatform.portfolio.note.serialization.NoteCommandFromApiJsonDeserializer; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccount; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccountRepository; -import org.mifosplatform.portfolio.savingsaccount.exception.SavingAccountNotFoundException; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccount; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountRepository; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccountNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -43,22 +37,21 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf private final NoteRepository noteRepository; private final ClientRepository clientRepository; private final GroupRepository groupRepository; - private final DepositAccountRepository depositAccountRepository; - private final SavingAccountRepository savingAccountRepository; + // private final SavingAccountRepository savingAccountRepository; private final LoanRepository loanRepository; private final LoanTransactionRepository loanTransactionRepository; private final NoteCommandFromApiJsonDeserializer fromApiJsonDeserializer; @Autowired public NoteWritePlatformServiceJpaRepositoryImpl(final NoteRepository noteRepository, final ClientRepository clientRepository, - final GroupRepository groupRepository, final DepositAccountRepository depositAccountRepository, - final SavingAccountRepository savingAccountRepository, final LoanRepository loanRepository, - final LoanTransactionRepository loanTransactionRepository, final NoteCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + final GroupRepository groupRepository, + // final SavingAccountRepository savingAccountRepository, + final LoanRepository loanRepository, final LoanTransactionRepository loanTransactionRepository, + final NoteCommandFromApiJsonDeserializer fromApiJsonDeserializer) { this.noteRepository = noteRepository; this.clientRepository = clientRepository; this.groupRepository = groupRepository; - this.depositAccountRepository = depositAccountRepository; - this.savingAccountRepository = savingAccountRepository; + // this.savingAccountRepository = savingAccountRepository; this.loanRepository = loanRepository; this.loanTransactionRepository = loanTransactionRepository; this.fromApiJsonDeserializer = fromApiJsonDeserializer; @@ -145,41 +138,26 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf .build(); } - private CommandProcessingResult createDepositAccountNote(final JsonCommand command) { - - final Long resourceId = command.getSupportedEntityId(); - - final DepositAccount depositAccount = this.depositAccountRepository.findOne(resourceId); - if (depositAccount == null) { throw new DepositAccountNotFoundException(resourceId); } - - final String note = command.stringValueOfParameterNamed("note"); - final Note newNote = Note.depositNote(depositAccount, note); - - this.noteRepository.save(newNote); - - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(newNote.getId()) // - .withClientId(depositAccount.client().getId()).withOfficeId(depositAccount.client().getOffice().getId()).build(); - } - - private CommandProcessingResult createSavingAccountNote(final JsonCommand command) { - - final Long resourceId = command.getSupportedEntityId(); - - final SavingAccount savingAccount = this.savingAccountRepository.findOne(resourceId); - if (savingAccount == null) { throw new SavingAccountNotFoundException(resourceId); } - - final String note = command.stringValueOfParameterNamed("note"); - final Note newNote = Note.savingNote(savingAccount, note); - - this.noteRepository.save(newNote); - - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(newNote.getId()) // - .withClientId(savingAccount.getClient().getId()).withOfficeId(savingAccount.getClient().getOffice().getId()).build(); - } + // private CommandProcessingResult createSavingAccountNote(final JsonCommand + // command) { + // + // final Long resourceId = command.getSupportedEntityId(); + // + // final SavingAccount savingAccount = + // this.savingAccountRepository.findOne(resourceId); + // if (savingAccount == null) { throw new + // SavingAccountNotFoundException(resourceId); } + // + // final String note = command.stringValueOfParameterNamed("note"); + // final Note newNote = Note.savingNote(savingAccount, note); + // + // this.noteRepository.save(newNote); + // + // return new CommandProcessingResultBuilder() // + // .withCommandId(command.commandId()) // + // .withEntityId(newNote.getId()) // + // .withClientId(savingAccount.getClient().getId()).withOfficeId(savingAccount.getClient().getOffice().getId()).build(); + // } @Override public CommandProcessingResult createNote(final JsonCommand command) { @@ -192,9 +170,6 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf case CLIENT: { return createClientNote(command); } - case DEPOSIT: { - return createDepositAccountNote(command); - } case GROUP: { return createGroupNote(command); } @@ -204,9 +179,9 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf case LOAN_TRANSACTION: { return createLoanTransactionNote(command); } - case SAVING: { - return createSavingAccountNote(command); - } + // case SAVING_ACCOUNT: { + // return createSavingAccountNote(command); + // } default: throw new NoteResourceNotSupportedException(resourceUrl); } @@ -236,40 +211,10 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(noteForUpdate.getId()) // - .withClientId(client.getId()).withOfficeId(client.getOffice().getId()) - .with(changes) - .build(); + .withClientId(client.getId()).withOfficeId(client.getOffice().getId()).with(changes).build(); } - private CommandProcessingResult updateDepositAccountNote(final JsonCommand command) { - - final Long resourceId = command.getSupportedEntityId(); - final Long noteId = command.entityId(); - final String resourceUrl = command.getSupportedEntityType(); - - final NoteType type = NoteType.fromApiUrl(resourceUrl); - - final DepositAccount depositAccount = this.depositAccountRepository.findOne(resourceId); - if (depositAccount == null) { throw new DepositAccountNotFoundException(resourceId); } - final Note noteForUpdate = this.noteRepository.findByDepositAccountIdAndId(resourceId, noteId); - - if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } - - final Map changes = noteForUpdate.update(command); - - if (!changes.isEmpty()) { - this.noteRepository.saveAndFlush(noteForUpdate); - } - - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(noteForUpdate.getId()) // - .withClientId(depositAccount.client().getId()).withOfficeId(depositAccount.client().getOffice().getId()) - .with(changes) - .build(); - } - private CommandProcessingResult updateGroupNote(final JsonCommand command) { final Long resourceId = command.getSupportedEntityId(); @@ -293,9 +238,7 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(noteForUpdate.getId()) // - .withGroupId(group.getId()).withOfficeId(group.getOfficeId()) - .with(changes) - .build(); + .withGroupId(group.getId()).withOfficeId(group.getOfficeId()).with(changes).build(); } private CommandProcessingResult updateLoanNote(final JsonCommand command) { @@ -320,8 +263,7 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(noteForUpdate.getId()) .withClientId(loan.getClientId()).withLoanId(loan.getId()).withGroupId(loan.getGroupId()).withOfficeId(loan.getOfficeId()) - .with(changes) - .build(); + .with(changes).build(); } private CommandProcessingResult updateLoanTransactionNote(final JsonCommand command) { @@ -348,38 +290,44 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(noteForUpdate.getId()) .withClientId(loan.getClientId()).withLoanId(loan.getId()).withGroupId(loan.getGroupId()).withOfficeId(loan.getOfficeId()) - .with(changes) - .build(); + .with(changes).build(); } - private CommandProcessingResult updateSavingAccountNote(final JsonCommand command) { - - final Long resourceId = command.getSupportedEntityId(); - final Long noteId = command.entityId(); - final String resourceUrl = command.getSupportedEntityType(); - - final NoteType type = NoteType.fromApiUrl(resourceUrl); - - final SavingAccount savingAccount = this.savingAccountRepository.findOne(resourceId); - if (savingAccount == null) { throw new SavingAccountNotFoundException(resourceId); } - - final Note noteForUpdate = this.noteRepository.findBySavingAccountIdAndId(resourceId, noteId); - - if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } - - final Map changes = noteForUpdate.update(command); - - if (!changes.isEmpty()) { - this.noteRepository.saveAndFlush(noteForUpdate); - } - - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(noteForUpdate.getId()) // - .withClientId(savingAccount.getClient().getId()).withOfficeId(savingAccount.getClient().getOffice().getId()) - .with(changes) - .build(); - } + // private CommandProcessingResult updateSavingAccountNote(final JsonCommand + // command) { + // + // final Long resourceId = command.getSupportedEntityId(); + // final Long noteId = command.entityId(); + // final String resourceUrl = command.getSupportedEntityType(); + // + // final NoteType type = NoteType.fromApiUrl(resourceUrl); + // + // final SavingAccount savingAccount = + // this.savingAccountRepository.findOne(resourceId); + // if (savingAccount == null) { throw new + // SavingAccountNotFoundException(resourceId); } + // + // final Note noteForUpdate = + // this.noteRepository.findBySavingAccountIdAndId(resourceId, noteId); + // + // if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, + // resourceId, type.name().toLowerCase()); } + // + // final Map changes = noteForUpdate.update(command); + // + // if (!changes.isEmpty()) { + // this.noteRepository.saveAndFlush(noteForUpdate); + // } + // + // return new CommandProcessingResultBuilder() + // // + // .withCommandId(command.commandId()) + // // + // .withEntityId(noteForUpdate.getId()) + // // + // .withClientId(savingAccount.getClient().getId()).withOfficeId(savingAccount.getClient().getOffice().getId()).with(changes) + // .build(); + // } @Override public CommandProcessingResult updateNote(final JsonCommand command) { @@ -393,9 +341,6 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf case CLIENT: { return updateClientNote(command); } - case DEPOSIT: { - return updateDepositAccountNote(command); - } case GROUP: { return updateGroupNote(command); } @@ -405,9 +350,9 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf case LOAN_TRANSACTION: { return updateLoanTransactionNote(command); } - case SAVING: { - return updateSavingAccountNote(command); - } + // case SAVING_ACCOUNT: { + // return updateSavingAccountNote(command); + // } default: throw new NoteResourceNotSupportedException(resourceUrl); } @@ -436,10 +381,6 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf noteForUpdate = this.noteRepository.findByClientIdAndId(resourceId, noteId); } break; - case DEPOSIT: { - noteForUpdate = this.noteRepository.findByDepositAccountIdAndId(resourceId, noteId); - } - break; case GROUP: { noteForUpdate = this.noteRepository.findByGroupIdAndId(resourceId, noteId); } @@ -452,9 +393,12 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf noteForUpdate = this.noteRepository.findByLoanTransactionIdAndId(resourceId, noteId); } break; - case SAVING: { - noteForUpdate = this.noteRepository.findBySavingAccountIdAndId(resourceId, noteId); - } + // case SAVING_ACCOUNT: { + // noteForUpdate = + // this.noteRepository.findBySavingAccountIdAndId(resourceId, noteId); + // } + // break; + case SAVING_ACCOUNT: break; } if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java new file mode 100644 index 000000000..358af459a --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java @@ -0,0 +1,168 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.api; + +import java.util.Collection; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.mifosplatform.commands.domain.CommandWrapper; +import org.mifosplatform.commands.service.CommandWrapperBuilder; +import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; +import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; +import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.portfolio.savings.data.SavingsAccountData; +import org.mifosplatform.portfolio.savings.data.SavingsProductData; +import org.mifosplatform.portfolio.savings.service.SavingsAccountReadPlatformService; +import org.mifosplatform.portfolio.savings.service.SavingsDropdownReadPlatformService; +import org.mifosplatform.portfolio.savings.service.SavingsProductReadPlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Path("/savingsaccounts") +@Component +@Scope("singleton") +public class SavingsAccountsApiResource { + + private final SavingsAccountReadPlatformService savingsAccountReadPlatformService; + private final SavingsProductReadPlatformService savingsProductReadPlatformService; + private final SavingsDropdownReadPlatformService dropdownReadPlatformService; + private final PlatformSecurityContext context; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final ApiRequestParameterHelper apiRequestParameterHelper; + + @Autowired + public SavingsAccountsApiResource(final SavingsAccountReadPlatformService savingsAccountReadPlatformService, + final SavingsProductReadPlatformService savingsProductReadPlatformService, + final SavingsDropdownReadPlatformService dropdownReadPlatformService, final PlatformSecurityContext context, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final ApiRequestParameterHelper apiRequestParameterHelper) { + this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; + this.savingsProductReadPlatformService = savingsProductReadPlatformService; + this.dropdownReadPlatformService = dropdownReadPlatformService; + this.context = context; + this.toApiJsonSerializer = toApiJsonSerializer; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.apiRequestParameterHelper = apiRequestParameterHelper; + } + + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String create(final String apiRequestBodyAsJson) { + + final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingsAccount().withJson(apiRequestBodyAsJson).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + } + + @PUT + @Path("{accountId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String update(@PathParam("accountId") final Long accountId, final String apiRequestBodyAsJson) { + + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSavingsAccount(accountId).withJson(apiRequestBodyAsJson) + .build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + + } + + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveAll(@Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + + final Collection products = this.savingsAccountReadPlatformService.retrieveAll(); + + final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, products, SavingsApiConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); + } + + @GET + @Path("{accountId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveOne(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + + SavingsAccountData savingsAccount = this.savingsAccountReadPlatformService.retrieveOne(accountId); + + final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + + if (settings.isTemplate()) { + savingsAccount = populateTemplateOptions(savingsAccount); + } + + return this.toApiJsonSerializer.serialize(settings, savingsAccount, SavingsApiConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); + } + + private SavingsAccountData populateTemplateOptions(final SavingsAccountData savingsAccount) { + + final Collection productOptions = this.savingsProductReadPlatformService.retrieveAllForLookup(); + final Collection interestRatePeriodFrequencyTypeOptions = this.dropdownReadPlatformService + .retrieveInterestRatePeriodFrequencyTypeOptions(); + final Collection lockinPeriodFrequencyTypeOptions = this.dropdownReadPlatformService + .retrieveLockinPeriodFrequencyTypeOptions(); + + return SavingsAccountData.withTemplateOptions(savingsAccount, productOptions, interestRatePeriodFrequencyTypeOptions, + lockinPeriodFrequencyTypeOptions); + } + + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveTemplate(@QueryParam("clientId") final Long clientId, @QueryParam("groupId") final Long groupId, + @QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + + final SavingsAccountData savingsAccount = this.savingsAccountReadPlatformService.retrieveTemplate(clientId, groupId, productId); + + final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, savingsAccount, SavingsApiConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); + } + + @DELETE + @Path("{accountId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String delete(@PathParam("accountId") final Long accountId) { + + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingsAccount(accountId).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsApiConstants.java new file mode 100644 index 000000000..0f8b0b384 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsApiConstants.java @@ -0,0 +1,63 @@ +package org.mifosplatform.portfolio.savings.api; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.mifosplatform.portfolio.savings.data.SavingsAccountData; +import org.mifosplatform.portfolio.savings.data.SavingsProductData; + +public class SavingsApiConstants { + + public static final String SAVINGS_PRODUCT_RESOURCE_NAME = "savingsproduct"; + public static final String SAVINGS_ACCOUNT_RESOURCE_NAME = "savingsaccount"; + + public static final String localeParamName = "locale"; + public static final String idParamName = "id"; + public static final String accountNoParamName = "accountNo"; + public static final String externalIdParamName = "externalId"; + public static final String clientIdParamName = "clientId"; + public static final String groupIdParamName = "groupId"; + public static final String productIdParamName = "productId"; + public static final String nameParamName = "name"; + public static final String descriptionParamName = "description"; + public static final String currencyCodeParamName = "currencyCode"; + public static final String digitsAfterDecimalParamName = "digitsAfterDecimal"; + public static final String interestRateParamName = "interestRate"; + public static final String interestRatePeriodFrequencyTypeParamName = "interestRatePeriodFrequencyType"; + public static final String minRequiredOpeningBalanceParamName = "minRequiredOpeningBalance"; + public static final String lockinPeriodFrequencyParamName = "lockinPeriodFrequency"; + public static final String lockinPeriodFrequencyTypeParamName = "lockinPeriodFrequencyType"; + + public static final Set SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, + nameParamName, descriptionParamName, currencyCodeParamName, digitsAfterDecimalParamName, interestRateParamName, + interestRatePeriodFrequencyTypeParamName, minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, + lockinPeriodFrequencyTypeParamName)); + + /** + * These parameters will match the class level parameters of + * {@link SavingsProductData}. Where possible, we try to get response + * parameters to match those of request parameters. + */ + public static final Set SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList(idParamName, + nameParamName, descriptionParamName, "currency", digitsAfterDecimalParamName, interestRateParamName, + interestRatePeriodFrequencyTypeParamName, minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, + lockinPeriodFrequencyTypeParamName, "currencyOptions", "interestRatePeriodFrequencyTypeOptions", + "lockinPeriodFrequencyTypeOptions")); + + public static final Set SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, + accountNoParamName, externalIdParamName, clientIdParamName, groupIdParamName, productIdParamName, interestRateParamName, + interestRatePeriodFrequencyTypeParamName, minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, + lockinPeriodFrequencyTypeParamName)); + + /** + * These parameters will match the class level parameters of + * {@link SavingsAccountData}. Where possible, we try to get response + * parameters to match those of request parameters. + */ + public static final Set SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList(idParamName, + accountNoParamName, externalIdParamName, clientIdParamName, "clientName", groupIdParamName, "groupName", "savingsProductId", + "savingsProductName", "currency", interestRateParamName, interestRatePeriodFrequencyTypeParamName, "annualInterestRate", + minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, "productOptions", + "interestRatePeriodFrequencyTypeOptions", "lockinPeriodFrequencyTypeOptions")); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/api/DepositProductsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java similarity index 52% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/api/DepositProductsApiResource.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java index ad13c33a7..9d1e8ed62 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/api/DepositProductsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java @@ -3,13 +3,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.mifosplatform.portfolio.savingsdepositproduct.api; +package org.mifosplatform.portfolio.savings.api; -import java.util.Arrays; import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -35,44 +31,38 @@ import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext import org.mifosplatform.organisation.monetary.data.CurrencyData; import org.mifosplatform.organisation.monetary.service.CurrencyReadPlatformService; import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingsDepositEnumerations; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductData; -import org.mifosplatform.portfolio.savingsdepositproduct.service.DepositProductReadPlatformService; +import org.mifosplatform.portfolio.savings.data.SavingsProductData; +import org.mifosplatform.portfolio.savings.service.SavingsDropdownReadPlatformService; +import org.mifosplatform.portfolio.savings.service.SavingsEnumerations; +import org.mifosplatform.portfolio.savings.service.SavingsProductReadPlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -@Path("/depositproducts") +@Path("/savingsproducts") @Component @Scope("singleton") -public class DepositProductsApiResource { +public class SavingsProductsApiResource { - private final Set DEPOSIT_PRODUCT_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "externalId", "name", - "description", "currencyCode", "digitsAfterDecimal", "minDeposit", "defaultDeposit", "maxDeposit", "tenureInMonths", - "defaultInterestRate", "minInterestRate", "maxInterestRate", "interestCompoundedEvery", - "interestCompoundedEveryPeriodType", "renewalAllowed", "preClosureAllowed", "preClosureInterestRate", - "interestCompoundingAllowed", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "currency", "currencyOptions", - "interestCompoundedEveryPeriodTypeOptions")); - - private final String entityType = "DEPOSITPRODUCT"; - - private final PlatformSecurityContext context; - private final DepositProductReadPlatformService depositProductReadPlatformService; + private final SavingsProductReadPlatformService savingProductReadPlatformService; + private final SavingsDropdownReadPlatformService dropdownReadPlatformService; private final CurrencyReadPlatformService currencyReadPlatformService; - private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final PlatformSecurityContext context; + private final DefaultToApiJsonSerializer toApiJsonSerializer; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final ApiRequestParameterHelper apiRequestParameterHelper; @Autowired - public DepositProductsApiResource(final PlatformSecurityContext context, - final DepositProductReadPlatformService depositProductReadPlatformService, - final CurrencyReadPlatformService currencyReadPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, + public SavingsProductsApiResource(final SavingsProductReadPlatformService savingProductReadPlatformService, + final SavingsDropdownReadPlatformService dropdownReadPlatformService, + final CurrencyReadPlatformService currencyReadPlatformService, final PlatformSecurityContext context, + final DefaultToApiJsonSerializer toApiJsonSerializer, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final ApiRequestParameterHelper apiRequestParameterHelper) { - this.context = context; - this.depositProductReadPlatformService = depositProductReadPlatformService; + this.savingProductReadPlatformService = savingProductReadPlatformService; + this.dropdownReadPlatformService = dropdownReadPlatformService; this.currencyReadPlatformService = currencyReadPlatformService; + this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.apiRequestParameterHelper = apiRequestParameterHelper; @@ -81,9 +71,9 @@ public class DepositProductsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String createDepositProduct(final String apiRequestBodyAsJson) { + public String create(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().createDepositProduct().withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingProduct().withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -94,79 +84,97 @@ public class DepositProductsApiResource { @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String updateDepositProduct(@PathParam("productId") final Long productId, final String apiRequestBodyAsJson) { + public String update(@PathParam("productId") final Long productId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDepositProduct(productId).withJson(apiRequestBodyAsJson) + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSavingProduct(productId).withJson(apiRequestBodyAsJson) .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); - } - @DELETE - @Path("{productId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String deleteDepositProduct(@PathParam("productId") final Long productId) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteDepositProduct(productId).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAllDepositProducts(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(entityType); - Collection products = this.depositProductReadPlatformService.retrieveAllDepositProducts(); + public String retrieveAll(@Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); + + final Collection products = this.savingProductReadPlatformService.retrieveAll(); + final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, products, DEPOSIT_PRODUCT_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, products, SavingsApiConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } @GET @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveDepositProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) { + public String retrieveOne(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); + + SavingsProductData savingProduct = this.savingProductReadPlatformService.retrieveOne(productId); - context.authenticatedUser().validateHasReadPermission(entityType); - DepositProductData productData = this.depositProductReadPlatformService.retrieveDepositProductData(productId); final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { - productData = handleTemplateRelatedData(productData); + savingProduct = handleTemplateRelatedData(savingProduct); } - return this.toApiJsonSerializer.serialize(settings, productData, DEPOSIT_PRODUCT_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, savingProduct, SavingsApiConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveNewDepositProductDetails(@Context final UriInfo uriInfo) { + public String retrieveTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(entityType); + context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); - DepositProductData depositProduct = this.depositProductReadPlatformService.retrieveNewDepositProductDetails(); - - depositProduct = handleTemplateRelatedData(depositProduct); + SavingsProductData savingProduct = handleTemplateRelatedData(null); final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, depositProduct, DEPOSIT_PRODUCT_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, savingProduct, SavingsApiConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } - private DepositProductData handleTemplateRelatedData(final DepositProductData productData) { + private SavingsProductData handleTemplateRelatedData(final SavingsProductData savingsProduct) { - Collection allowedCurrencies = this.currencyReadPlatformService.retrieveAllowedCurrencies(); + final EnumOptionData interestRatePeriodFrequencyType = SavingsEnumerations + .interestRatePeriodFrequencyType(PeriodFrequencyType.YEARS); - EnumOptionData monthly = SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType.MONTHS); - List interestCompoundedEveryPeriodTypeOptions = Arrays.asList(monthly); + final Collection currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); + final Collection interestRatePeriodFrequencyTypeOptions = this.dropdownReadPlatformService + .retrieveInterestRatePeriodFrequencyTypeOptions(); + final Collection lockinPeriodFrequencyTypeOptions = this.dropdownReadPlatformService + .retrieveLockinPeriodFrequencyTypeOptions(); + + SavingsProductData savingsProductToReturn = null; + if (savingsProduct != null) { + savingsProductToReturn = SavingsProductData.withTemplate(savingsProduct, currencyOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } else { + savingsProductToReturn = SavingsProductData.template(CurrencyData.blank(), interestRatePeriodFrequencyType, currencyOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } + + return savingsProductToReturn; + } + + @DELETE + @Path("{productId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String delete(@PathParam("productId") final Long productId) { + + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingProduct(productId).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + + return this.toApiJsonSerializer.serialize(result); - return new DepositProductData(productData, allowedCurrencies, interestCompoundedEveryPeriodTypeOptions); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java new file mode 100644 index 000000000..6ccfd7368 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java @@ -0,0 +1,123 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.data; + +import java.math.BigDecimal; +import java.util.Collection; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.organisation.monetary.data.CurrencyData; + +/** + * Immutable data object representing a savings account. + */ +@SuppressWarnings("unused") +public class SavingsAccountData { + + private final Long id; + private final String accountNo; + private final String externalId; + private final Long groupId; + private final String groupName; + private final Long clientId; + private final String clientName; + private final Long savingsProductId; + private final String savingsProductName; + private final CurrencyData currency; + private final BigDecimal interestRate; + private final EnumOptionData interestRatePeriodFrequencyType; + private final BigDecimal annualInterestRate; + private final BigDecimal minRequiredOpeningBalance; + private final Integer lockinPeriodFrequency; + private final EnumOptionData lockinPeriodFrequencyType; + + // template + private final Collection productOptions; + private final Collection interestRatePeriodFrequencyTypeOptions; + private final Collection lockinPeriodFrequencyTypeOptions; + + public static SavingsAccountData instance(final Long id, final String accountNo, final String externalId, final Long groupId, + final String groupName, final Long clientId, final String clientName, final Long productId, final String productName, + final CurrencyData currency, final BigDecimal interestRate, final EnumOptionData interestRatePeriodFrequencyType, + final BigDecimal annualInterestRate, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, + final EnumOptionData lockinPeriodFrequencyType) { + + final Collection productOptions = null; + final Collection interestRatePeriodFrequencyTypeOptions = null; + final Collection lockinPeriodFrequencyTypeOptions = null; + + return new SavingsAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, + currency, interestRate, interestRatePeriodFrequencyType, annualInterestRate, minRequiredOpeningBalance, + lockinPeriodFrequency, lockinPeriodFrequencyType, productOptions, interestRatePeriodFrequencyTypeOptions, + lockinPeriodFrequencyTypeOptions); + } + + public static SavingsAccountData withTemplateOptions(final SavingsAccountData account, + final Collection productOptions, final Collection interestRatePeriodFrequencyTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions) { + + return new SavingsAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName, + account.clientId, account.clientName, account.savingsProductId, account.savingsProductName, account.currency, + account.interestRate, account.interestRatePeriodFrequencyType, account.annualInterestRate, + account.minRequiredOpeningBalance, account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, productOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } + + public static SavingsAccountData withClientTemplate(final Long clientId, final String clientName, final Long groupId, + final String groupName) { + + final Long id = null; + final String accountNo = null; + final String externalId = null; + final Long productId = null; + final String productName = null; + final CurrencyData currency = null; + final BigDecimal interestRate = null; + final EnumOptionData interestRatePeriodFrequencyType = null; + final BigDecimal annualInterestRate = null; + final BigDecimal minRequiredOpeningBalance = null; + final Integer lockinPeriodFrequency = null; + final EnumOptionData lockinPeriodFrequencyType = null; + final Collection productOptions = null; + final Collection currencyOptions = null; + final Collection interestRatePeriodFrequencyTypeOptions = null; + final Collection lockinPeriodFrequencyTypeOptions = null; + + return new SavingsAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, + currency, interestRate, interestRatePeriodFrequencyType, annualInterestRate, minRequiredOpeningBalance, + lockinPeriodFrequency, lockinPeriodFrequencyType, productOptions, interestRatePeriodFrequencyTypeOptions, + lockinPeriodFrequencyTypeOptions); + } + + private SavingsAccountData(final Long id, final String accountNo, final String externalId, final Long groupId, final String groupName, + final Long clientId, final String clientName, final Long productId, final String productName, final CurrencyData currency, + final BigDecimal interestRate, final EnumOptionData interestRatePeriodFrequencyType, final BigDecimal annualInterestRate, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, + final EnumOptionData lockinPeriodFrequencyType, final Collection productOptions, + final Collection interestRatePeriodFrequencyTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions) { + this.id = id; + this.accountNo = accountNo; + this.externalId = externalId; + this.groupId = groupId; + this.groupName = groupName; + this.clientId = clientId; + this.clientName = clientName; + this.savingsProductId = productId; + this.savingsProductName = productName; + this.currency = currency; + this.interestRate = interestRate; + this.interestRatePeriodFrequencyType = interestRatePeriodFrequencyType; + this.annualInterestRate = annualInterestRate; + this.minRequiredOpeningBalance = minRequiredOpeningBalance; + this.lockinPeriodFrequency = lockinPeriodFrequency; + this.lockinPeriodFrequencyType = lockinPeriodFrequencyType; + + this.productOptions = productOptions; + this.interestRatePeriodFrequencyTypeOptions = interestRatePeriodFrequencyTypeOptions; + this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java new file mode 100644 index 000000000..e6525ab33 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java @@ -0,0 +1,244 @@ +package org.mifosplatform.portfolio.savings.data; + +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.accountNoParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.clientIdParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.externalIdParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.groupIdParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRateParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRatePeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.minRequiredOpeningBalanceParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.productIdParamName; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.mifosplatform.infrastructure.core.data.ApiParameterError; +import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; +import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; +import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.mifosplatform.portfolio.savings.api.SavingsApiConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; + +@Component +public class SavingsAccountDataValidator { + + private final FromJsonHelper fromApiJsonHelper; + + @Autowired + public SavingsAccountDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } + + public void validateForCreate(final String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); + + final List dataValidationErrors = new ArrayList(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + + final JsonElement element = fromApiJsonHelper.parse(json); + final Long clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + if (clientId != null) { + baseDataValidator.reset().parameter(clientIdParamName).value(clientId).longGreaterThanZero(); + } + + final Long groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + if (groupId != null) { + baseDataValidator.reset().parameter(groupIdParamName).value(groupId).longGreaterThanZero(); + } + + if (clientId == null && groupId == null) { + baseDataValidator.reset().parameter(clientIdParamName).value(clientId).notNull().integerGreaterThanZero(); + } + + final Long productId = fromApiJsonHelper.extractLongNamed(productIdParamName, element); + baseDataValidator.reset().parameter(productIdParamName).value(productId).notNull().integerGreaterThanZero(); + + if (fromApiJsonHelper.parameterExists(accountNoParamName, element)) { + final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParamName, element); + baseDataValidator.reset().parameter(accountNoParamName).value(accountNo).notBlank().notExceedingLengthOf(20); + } + + if (fromApiJsonHelper.parameterExists(externalIdParamName, element)) { + final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParamName, element); + baseDataValidator.reset().parameter(externalIdParamName).value(externalId).notExceedingLengthOf(100); + } + + if (fromApiJsonHelper.parameterExists(interestRateParamName, element)) { + final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRateParamName, element); + baseDataValidator.reset().parameter(interestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); + } + + if (fromApiJsonHelper.parameterExists(interestRatePeriodFrequencyTypeParamName, element)) { + final Integer interestRatePeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + interestRatePeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(interestRatePeriodFrequencyTypeParamName).value(interestRatePeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + } + + if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { + final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); + baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).positiveAmount(); + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { + + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() + .positiveAmount(); + + if (lockinPeriodFrequency != null) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + } + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(1, 3); + + if (lockinPeriodFrequencyType != null) { + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).notNull().positiveAmount(); + } + } + + throwExceptionIfValidationWarningsExist(dataValidationErrors); + } + + public void validateForUpdate(final String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); + + final List dataValidationErrors = new ArrayList(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + + final JsonElement element = fromApiJsonHelper.parse(json); + + Long clientId = null; + if (fromApiJsonHelper.parameterExists(clientIdParamName, element)) { + clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + baseDataValidator.reset().parameter(clientIdParamName).value(clientId).ignoreIfNull().longGreaterThanZero(); + + Long groupId = null; + if (fromApiJsonHelper.parameterExists(productIdParamName, element)) { + groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + baseDataValidator.reset().parameter(groupIdParamName).value(groupId).ignoreIfNull().longGreaterThanZero(); + } + + if (clientId == null && groupId == null) { + // either clientId or groupId must exists if param passed for + // update. + baseDataValidator.reset().parameter(clientIdParamName).value(clientId).notNull().integerGreaterThanZero(); + } + } + + Long groupId = null; + if (fromApiJsonHelper.parameterExists(groupIdParamName, element)) { + groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + baseDataValidator.reset().parameter(groupIdParamName).value(groupId).ignoreIfNull().longGreaterThanZero(); + + if (fromApiJsonHelper.parameterExists(clientIdParamName, element)) { + clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + baseDataValidator.reset().parameter(clientIdParamName).value(clientId).ignoreIfNull().longGreaterThanZero(); + } + + if (clientId == null && groupId == null) { + // either clientId or groupId must exists if param passed for + // update. + baseDataValidator.reset().parameter(clientIdParamName).value(clientId).notNull().integerGreaterThanZero(); + } + } + + if (fromApiJsonHelper.parameterExists(productIdParamName, element)) { + final Long productId = fromApiJsonHelper.extractLongNamed(productIdParamName, element); + baseDataValidator.reset().parameter(productIdParamName).value(productId).notNull().integerGreaterThanZero(); + } + + if (fromApiJsonHelper.parameterExists(accountNoParamName, element)) { + final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParamName, element); + baseDataValidator.reset().parameter(accountNoParamName).value(accountNo).notBlank().notExceedingLengthOf(20); + } + + if (fromApiJsonHelper.parameterExists(externalIdParamName, element)) { + final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParamName, element); + baseDataValidator.reset().parameter(externalIdParamName).value(externalId).notExceedingLengthOf(100); + } + + if (fromApiJsonHelper.parameterExists(interestRateParamName, element)) { + final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRateParamName, element); + baseDataValidator.reset().parameter(interestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); + } + + if (fromApiJsonHelper.parameterExists(interestRatePeriodFrequencyTypeParamName, element)) { + final Integer interestRatePeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + interestRatePeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(interestRatePeriodFrequencyTypeParamName).value(interestRatePeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + } + + if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { + final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); + baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).positiveAmount(); + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { + + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() + .positiveAmount(); + + if (lockinPeriodFrequency != null) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + } + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(1, 3); + + if (lockinPeriodFrequencyType != null) { + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).notNull().positiveAmount(); + } + } + + throwExceptionIfValidationWarningsExist(dataValidationErrors); + + } + + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java new file mode 100644 index 000000000..0a62f7765 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java @@ -0,0 +1,119 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.data; + +import java.math.BigDecimal; +import java.util.Collection; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.organisation.monetary.data.CurrencyData; + +/** + * Immutable data object represent a savings product. + */ +@SuppressWarnings("unused") +public class SavingsProductData { + + private final Long id; + private final String name; + private final String description; + private final CurrencyData currency; + private final BigDecimal interestRate; + private final EnumOptionData interestRatePeriodFrequencyType; + private final BigDecimal minRequiredOpeningBalance; + private final Integer lockinPeriodFrequency; + private final EnumOptionData lockinPeriodFrequencyType; + + // template + private final Collection currencyOptions; + private final Collection interestRatePeriodFrequencyTypeOptions; + private final Collection lockinPeriodFrequencyTypeOptions; + + public static SavingsProductData template(final CurrencyData currency, final EnumOptionData interestRatePeriodFrequencyType, + final Collection currencyOptions, final Collection interestRatePeriodFrequencyTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions) { + + final Long id = null; + final String name = null; + final String description = null; + final Integer digitsAfterDecimal = null; + final BigDecimal interestRate = null; + final BigDecimal minRequiredOpeningBalance = null; + final Integer lockinPeriodFrequency = null; + final EnumOptionData lockinPeriodFrequencyType = null; + + return new SavingsProductData(id, name, description, currency, interestRate, interestRatePeriodFrequencyType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, currencyOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } + + /** + * Returns a {@link SavingsProductData} that contains and exist + * {@link SavingsProductData} data with further template data for dropdowns. + */ + public static SavingsProductData withTemplate(final SavingsProductData existingProduct, final Collection currencyOptions, + final Collection interestRatePeriodFrequencyTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions) { + + return new SavingsProductData(existingProduct.id, existingProduct.name, existingProduct.description, existingProduct.currency, + existingProduct.interestRate, existingProduct.interestRatePeriodFrequencyType, existingProduct.minRequiredOpeningBalance, + existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, currencyOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } + + public static SavingsProductData instance(final Long id, final String name, final String description, final CurrencyData currency, + final BigDecimal interestRate, final EnumOptionData interestRatePeriodFrequencyType, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType) { + + final Collection currencyOptions = null; + final Collection interestRatePeriodFrequencyTypeOptions = null; + final Collection lockinPeriodFrequencyTypeOptions = null; + + return new SavingsProductData(id, name, description, currency, interestRate, interestRatePeriodFrequencyType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, currencyOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } + + public static SavingsProductData lookup(final Long id, final String name) { + + final CurrencyData currency = null; + final String description = null; + final BigDecimal interestRate = null; + final EnumOptionData interestRatePeriodFrequencyType = null; + final BigDecimal minRequiredOpeningBalance = null; + final Integer lockinPeriodFrequency = null; + final EnumOptionData lockinPeriodFrequencyType = null; + + final Collection currencyOptions = null; + final Collection interestRatePeriodFrequencyTypeOptions = null; + final Collection lockinPeriodFrequencyTypeOptions = null; + + return new SavingsProductData(id, name, description, currency, interestRate, interestRatePeriodFrequencyType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, currencyOptions, + interestRatePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions); + } + + private SavingsProductData(final Long id, final String name, final String description, final CurrencyData currency, + final BigDecimal interestRate, final EnumOptionData interestRatePeriodFrequencyType, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, + final EnumOptionData lockinPeriodFrequencyType, final Collection currencyOptions, + final Collection interestRatePeriodFrequencyTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions) { + this.id = id; + this.name = name; + this.description = description; + this.currency = currency; + this.interestRate = interestRate; + this.interestRatePeriodFrequencyType = interestRatePeriodFrequencyType; + this.minRequiredOpeningBalance = minRequiredOpeningBalance; + this.lockinPeriodFrequency = lockinPeriodFrequency; + this.lockinPeriodFrequencyType = lockinPeriodFrequencyType; + + this.currencyOptions = currencyOptions; + this.interestRatePeriodFrequencyTypeOptions = interestRatePeriodFrequencyTypeOptions; + this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java new file mode 100644 index 000000000..073a1c6c7 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java @@ -0,0 +1,172 @@ +package org.mifosplatform.portfolio.savings.data; + +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.currencyCodeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.descriptionParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.digitsAfterDecimalParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRateParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRatePeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.minRequiredOpeningBalanceParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.nameParamName; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.mifosplatform.infrastructure.core.data.ApiParameterError; +import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; +import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; +import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; + +@Component +public class SavingsProductDataValidator { + + private final FromJsonHelper fromApiJsonHelper; + + @Autowired + public SavingsProductDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } + + public void validateForCreate(final String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS); + + final List dataValidationErrors = new ArrayList(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(SAVINGS_PRODUCT_RESOURCE_NAME); + final JsonElement element = fromApiJsonHelper.parse(json); + + final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); + baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); + + final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); + baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); + + final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); + baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); + + final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); + baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); + + final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRateParamName, element); + baseDataValidator.reset().parameter(interestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); + + final Integer interestRatePeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + interestRatePeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(interestRatePeriodFrequencyTypeParamName).value(interestRatePeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + + if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { + final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); + baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).positiveAmount(); + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { + + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() + .positiveAmount(); + + if (lockinPeriodFrequency != null) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + } + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(1, 3); + + if (lockinPeriodFrequencyType != null) { + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).notNull().positiveAmount(); + } + } + + throwExceptionIfValidationWarningsExist(dataValidationErrors); + } + + public void validateForUpdate(final String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS); + + final List dataValidationErrors = new ArrayList(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(SAVINGS_PRODUCT_RESOURCE_NAME); + final JsonElement element = fromApiJsonHelper.parse(json); + + if (this.fromApiJsonHelper.parameterExists(nameParamName, element)) { + final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); + baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); + } + + if (this.fromApiJsonHelper.parameterExists(descriptionParamName, element)) { + final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); + baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); + } + + if (this.fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { + final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); + baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); + } + + if (this.fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { + final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); + baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); + } + + if (this.fromApiJsonHelper.parameterExists(interestRateParamName, element)) { + final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRateParamName, element); + baseDataValidator.reset().parameter(interestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); + } + + if (this.fromApiJsonHelper.parameterExists(interestRatePeriodFrequencyTypeParamName, element)) { + final Integer interestRatePeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + interestRatePeriodFrequencyTypeParamName, element); + baseDataValidator.reset().parameter(interestRatePeriodFrequencyTypeParamName).value(interestRatePeriodFrequencyType).notNull() + .inMinMaxRange(1, 3); + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { + + final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() + .positiveAmount(); + } + + if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { + final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, + element); + baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(1, 3); + } + + throwExceptionIfValidationWarningsExist(dataValidationErrors); + } + + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java new file mode 100644 index 000000000..c1d4cc605 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java @@ -0,0 +1,235 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.domain; + +import java.math.BigDecimal; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.persistence.UniqueConstraint; + +import org.apache.commons.lang.StringUtils; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.security.service.RandomPasswordGenerator; +import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; +import org.mifosplatform.organisation.monetary.domain.Money; +import org.mifosplatform.portfolio.client.domain.Client; +import org.mifosplatform.portfolio.group.domain.Group; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.mifosplatform.portfolio.savings.api.SavingsApiConstants; +import org.springframework.data.jpa.domain.AbstractPersistable; + +@Entity +@Table(name = "m_savings_account", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_no" }, name = "sa_account_no_UNIQUE"), + @UniqueConstraint(columnNames = { "external_id" }, name = "sa_external_id_UNIQUE") }) +public class SavingsAccount extends AbstractPersistable { + + @Column(name = "account_no", length = 20, unique = true, nullable = false) + private String accountNumber; + + @Column(name = "external_id") + private String externalId; + + @ManyToOne(optional = true) + @JoinColumn(name = "client_id", nullable = true) + private Client client; + + @ManyToOne(optional = true) + @JoinColumn(name = "group_id", nullable = true) + private Group group; + + @ManyToOne + @JoinColumn(name = "product_id", nullable = false) + private SavingsProduct product; + + @Embedded + private MonetaryCurrency currency; + + @Column(name = "nominal_interest_rate_per_period", scale = 6, precision = 19, nullable = false) + private BigDecimal interestRate; + + @Column(name = "nominal_interest_rate_period_frequency_enum", nullable = false) + private Integer interestRatePeriodFrequencyType; + + @SuppressWarnings("unused") + @Column(name = "annual_nominal_interest_rate", scale = 6, precision = 19, nullable = false) + private BigDecimal annualInterestRate; + + @Column(name = "min_required_opening_balance", scale = 6, precision = 19, nullable = false) + private BigDecimal minRequiredOpeningBalance; + + @Column(name = "lockin_period_frequency", nullable = false) + private Integer lockinPeriodFrequency; + + @Column(name = "lockin_period_frequency_enum", nullable = false) + private Integer lockinPeriodFrequencyType; + + @Transient + private boolean accountNumberRequiresAutoGeneration = false; + + protected SavingsAccount() { + // + } + + public static SavingsAccount createNewAccount(final Client client, final Group group, final SavingsProduct product, + final String accountNo, final String externalId, final BigDecimal interestRate, + final PeriodFrequencyType interestRatePeriodFrequencyType, final BigDecimal annualInterestRate, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, + final PeriodFrequencyType lockinPeriodFrequencyType) { + + return new SavingsAccount(client, group, product, accountNo, externalId, interestRate, interestRatePeriodFrequencyType, + annualInterestRate, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType); + } + + private SavingsAccount(final Client client, final Group group, final SavingsProduct product, final String accountNo, + final String externalId, final BigDecimal interestRate, final PeriodFrequencyType interestRatePeriodFrequencyType, + final BigDecimal annualInterestRate, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, + final PeriodFrequencyType lockinPeriodFrequencyType) { + this.client = client; + this.group = group; + this.product = product; + if (StringUtils.isBlank(accountNo)) { + this.accountNumber = new RandomPasswordGenerator(19).generate(); + this.accountNumberRequiresAutoGeneration = true; + } else { + this.accountNumber = accountNo; + } + this.currency = product.currency(); + this.externalId = externalId; + this.interestRate = interestRate; + this.interestRatePeriodFrequencyType = interestRatePeriodFrequencyType.getValue(); + this.annualInterestRate = annualInterestRate; + this.minRequiredOpeningBalance = minRequiredOpeningBalance; + this.lockinPeriodFrequency = lockinPeriodFrequency; + if (lockinPeriodFrequencyType != null) { + this.lockinPeriodFrequencyType = lockinPeriodFrequencyType.getValue(); + } + } + + public void update(final JsonCommand command, final Map actualChanges) { + + final String localeAsInput = command.locale(); + + if (command.isChangeInStringParameterNamed(SavingsApiConstants.accountNoParamName, this.accountNumber)) { + final String newValue = command.stringValueOfParameterNamed(SavingsApiConstants.accountNoParamName); + actualChanges.put(SavingsApiConstants.accountNoParamName, newValue); + this.accountNumber = StringUtils.defaultIfEmpty(newValue, null); + } + + if (command.isChangeInStringParameterNamed(SavingsApiConstants.externalIdParamName, this.externalId)) { + final String newValue = command.stringValueOfParameterNamed(SavingsApiConstants.externalIdParamName); + actualChanges.put(SavingsApiConstants.externalIdParamName, newValue); + this.externalId = StringUtils.defaultIfEmpty(newValue, null); + } + + if (command.isChangeInLongParameterNamed(SavingsApiConstants.clientIdParamName, clientId())) { + final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.clientIdParamName); + actualChanges.put(SavingsApiConstants.clientIdParamName, newValue); + } + + if (command.isChangeInLongParameterNamed(SavingsApiConstants.groupIdParamName, groupId())) { + final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); + actualChanges.put(SavingsApiConstants.groupIdParamName, newValue); + } + + if (command.isChangeInLongParameterNamed(SavingsApiConstants.productIdParamName, this.product.getId())) { + final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.productIdParamName); + actualChanges.put(SavingsApiConstants.productIdParamName, newValue); + } + + if (command.isChangeInBigDecimalParameterNamed(SavingsApiConstants.interestRateParamName, this.interestRate)) { + final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(SavingsApiConstants.interestRateParamName); + actualChanges.put(SavingsApiConstants.interestRateParamName, newValue); + actualChanges.put("locale", localeAsInput); + this.interestRate = newValue; + } + + if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestRatePeriodFrequencyTypeParamName, + this.interestRatePeriodFrequencyType)) { + final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestRatePeriodFrequencyTypeParamName); + actualChanges.put(SavingsApiConstants.interestRatePeriodFrequencyTypeParamName, newValue); + this.interestRatePeriodFrequencyType = PeriodFrequencyType.fromInt(newValue).getValue(); + } + + if (command.isChangeInBigDecimalParameterNamed(SavingsApiConstants.minRequiredOpeningBalanceParamName, + this.minRequiredOpeningBalance)) { + final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(SavingsApiConstants.minRequiredOpeningBalanceParamName); + actualChanges.put(SavingsApiConstants.minRequiredOpeningBalanceParamName, newValue); + actualChanges.put("locale", localeAsInput); + this.minRequiredOpeningBalance = Money.of(this.currency, newValue).getAmount(); + } + + if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.lockinPeriodFrequencyParamName, this.lockinPeriodFrequency)) { + final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.lockinPeriodFrequencyParamName); + actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyParamName, newValue); + actualChanges.put("locale", localeAsInput); + this.lockinPeriodFrequency = newValue; + } + + if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, this.lockinPeriodFrequencyType)) { + final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName); + actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, newValue); + if (newValue != null) { + this.lockinPeriodFrequencyType = PeriodFrequencyType.fromInt(newValue).getValue(); + } else { + this.lockinPeriodFrequencyType = null; + } + } + } + + public void update(final Client client) { + this.client = client; + } + + public void update(final Group group) { + this.group = group; + } + + public void update(final SavingsProduct product) { + this.product = product; + } + + public void updateAccountNo(final String newAccountNo) { + this.accountNumber = newAccountNo; + this.accountNumberRequiresAutoGeneration = false; + } + + public boolean isAccountNumberRequiresAutoGeneration() { + return this.accountNumberRequiresAutoGeneration; + } + + public Long officeId() { + Long officeId = null; + if (this.client != null) { + officeId = this.client.officeId(); + } else { + officeId = this.group.officeId(); + } + return officeId; + } + + public Long clientId() { + Long id = null; + if (this.client != null) { + id = this.client.getId(); + } + return id; + } + + public Long groupId() { + Long id = null; + if (this.group != null) { + id = this.group.getId(); + } + return id; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java new file mode 100644 index 000000000..c83482883 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java @@ -0,0 +1,132 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.domain; + +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRateParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRatePeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.minRequiredOpeningBalanceParamName; + +import java.math.BigDecimal; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; +import org.mifosplatform.portfolio.client.domain.Client; +import org.mifosplatform.portfolio.client.domain.ClientRepository; +import org.mifosplatform.portfolio.client.exception.ClientNotFoundException; +import org.mifosplatform.portfolio.group.domain.Group; +import org.mifosplatform.portfolio.group.domain.GroupRepository; +import org.mifosplatform.portfolio.group.exception.GroupNotFoundException; +import org.mifosplatform.portfolio.loanaccount.loanschedule.domain.AprCalculator; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.mifosplatform.portfolio.savings.exception.SavingsProductNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.google.gson.JsonElement; + +@Service +public class SavingsAccountAssembler { + + private final ClientRepository clientRepository; + private final GroupRepository groupRepository; + private final SavingsProductRepository savingProductRepository; + private final FromJsonHelper fromApiJsonHelper; + private final AprCalculator aprCalculator; + + @Autowired + public SavingsAccountAssembler(final ClientRepository clientRepository, final GroupRepository groupRepository, + final SavingsProductRepository savingProductRepository, final AprCalculator aprCalculator, + final FromJsonHelper fromApiJsonHelper) { + this.clientRepository = clientRepository; + this.groupRepository = groupRepository; + this.savingProductRepository = savingProductRepository; + this.aprCalculator = aprCalculator; + this.fromApiJsonHelper = fromApiJsonHelper; + } + + /** + * Assembles a new {@link SavingsAccount} from JSON details passed in + * request inheriting details where relevant from chosen + * {@link SavingsProduct}. + */ + public SavingsAccount assembleFrom(final JsonCommand command) { + + final JsonElement element = command.parsedJson(); + + final String accountNo = fromApiJsonHelper.extractStringNamed("accountNo", element); + final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); + final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); + + final SavingsProduct product = this.savingProductRepository.findOne(productId); + if (product == null) { throw new SavingsProductNotFoundException(productId); } + + final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); + final Long groupId = fromApiJsonHelper.extractLongNamed("groupId", element); + + Client client = null; + Group group = null; + if (clientId != null) { + client = this.clientRepository.findOne(clientId); + if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } + } + + if (groupId != null) { + group = this.groupRepository.findOne(groupId); + if (group == null || group.isDeleted()) { throw new GroupNotFoundException(groupId); } + } + + BigDecimal interestRate = null; + if (command.parameterExists(interestRateParamName)) { + interestRate = command.bigDecimalValueOfParameterNamed(interestRateParamName); + } else { + interestRate = product.interestRate(); + } + + PeriodFrequencyType interestRatePeriodFrequencyType = null; + Integer interestRatePeriodFrequencyTypeValue = null; + if (command.parameterExists(interestRatePeriodFrequencyTypeParamName)) { + interestRatePeriodFrequencyTypeValue = command.integerValueOfParameterNamed(interestRatePeriodFrequencyTypeParamName); + if (interestRatePeriodFrequencyTypeValue != null) { + interestRatePeriodFrequencyType = PeriodFrequencyType.fromInt(interestRatePeriodFrequencyTypeValue); + } + } else { + interestRatePeriodFrequencyType = product.interestRatePeriodFrequencyType(); + } + + final BigDecimal annualInterestRate = this.aprCalculator.calculateFrom(interestRatePeriodFrequencyType, interestRate); + + BigDecimal minRequiredOpeningBalance = null; + if (command.parameterExists(minRequiredOpeningBalanceParamName)) { + minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); + } else { + minRequiredOpeningBalance = product.minRequiredOpeningBalance(); + } + + Integer lockinPeriodFrequency = null; + if (command.parameterExists(lockinPeriodFrequencyParamName)) { + lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); + } else { + lockinPeriodFrequency = product.lockinPeriodFrequency(); + } + + PeriodFrequencyType lockinPeriodFrequencyType = null; + Integer lockinPeriodFrequencyTypeValue = null; + if (command.parameterExists(lockinPeriodFrequencyTypeParamName)) { + lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); + if (lockinPeriodFrequencyTypeValue != null) { + lockinPeriodFrequencyType = PeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); + } + } else { + lockinPeriodFrequencyType = product.lockinPeriodFrequencyType(); + } + + return SavingsAccount.createNewAccount(client, group, product, accountNo, externalId, interestRate, + interestRatePeriodFrequencyType, annualInterestRate, minRequiredOpeningBalance, lockinPeriodFrequency, + lockinPeriodFrequencyType); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java similarity index 65% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountRepository.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java index 54305fd69..c728382b8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java @@ -3,11 +3,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.mifosplatform.portfolio.savingsaccount.domain; +package org.mifosplatform.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface SavingAccountRepository extends JpaRepository, JpaSpecificationExecutor { +public interface SavingsAccountRepository extends JpaRepository, JpaSpecificationExecutor { } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java new file mode 100644 index 000000000..af4b2af19 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java @@ -0,0 +1,215 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.domain; + +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.currencyCodeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.descriptionParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.digitsAfterDecimalParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRateParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRatePeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.localeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.minRequiredOpeningBalanceParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.nameParamName; + +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.Table; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; +import org.mifosplatform.organisation.monetary.domain.Money; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.mifosplatform.portfolio.savings.exception.InvalidSavingsProductSettingsException; +import org.springframework.data.jpa.domain.AbstractPersistable; + +@Entity +@Table(name = "m_savings_product") +public class SavingsProduct extends AbstractPersistable { + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "description", length = 500, nullable = false) + private String description; + + @Embedded + private MonetaryCurrency currency; + + @Column(name = "nominal_interest_rate_per_period", scale = 6, precision = 19, nullable = false) + private BigDecimal interestRate; + + @Column(name = "nominal_interest_rate_period_frequency_enum", nullable = false) + private Integer interestRatePeriodFrequencyType; + + @Column(name = "min_required_opening_balance", scale = 6, precision = 19, nullable = false) + private BigDecimal minRequiredOpeningBalance; + + @Column(name = "lockin_period_frequency", nullable = false) + private Integer lockinPeriodFrequency; + + @Column(name = "lockin_period_frequency_enum", nullable = false) + private Integer lockinPeriodFrequencyType; + + public static SavingsProduct createNew(final String name, final String description, final MonetaryCurrency currency, + final BigDecimal interestRate, final PeriodFrequencyType interestRatePeriodFrequencyType, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, + final PeriodFrequencyType lockinPeriodFrequencyType) { + + return new SavingsProduct(name, description, currency, interestRate, interestRatePeriodFrequencyType, minRequiredOpeningBalance, + lockinPeriodFrequency, lockinPeriodFrequencyType); + } + + protected SavingsProduct() { + this.name = null; + this.description = null; + } + + private SavingsProduct(final String name, final String description, final MonetaryCurrency currency, final BigDecimal interestRate, + final PeriodFrequencyType interestRatePeriodFrequencyType, final BigDecimal minRequiredOpeningBalance, + final Integer lockinPeriodFrequency, final PeriodFrequencyType lockinPeriodFrequencyType) { + + this.name = name; + this.description = description; + + this.currency = currency; + this.interestRate = interestRate; + this.interestRatePeriodFrequencyType = interestRatePeriodFrequencyType.getValue(); + + if (minRequiredOpeningBalance != null) { + this.minRequiredOpeningBalance = Money.of(currency, minRequiredOpeningBalance).getAmount(); + } + + this.lockinPeriodFrequency = lockinPeriodFrequency; + if (lockinPeriodFrequencyType != null) { + this.lockinPeriodFrequencyType = lockinPeriodFrequencyType.getValue(); + } + + validateLockinDetails(); + } + + public MonetaryCurrency currency() { + return this.currency.copy(); + } + + public BigDecimal interestRate() { + return Money.of(this.currency, this.interestRate).getAmount(); + } + + public PeriodFrequencyType interestRatePeriodFrequencyType() { + PeriodFrequencyType type = null; + if (this.interestRatePeriodFrequencyType != null) { + type = PeriodFrequencyType.fromInt(this.interestRatePeriodFrequencyType); + } + return type; + } + + public BigDecimal minRequiredOpeningBalance() { + return this.minRequiredOpeningBalance; + } + + public Integer lockinPeriodFrequency() { + return this.lockinPeriodFrequency; + } + + public PeriodFrequencyType lockinPeriodFrequencyType() { + PeriodFrequencyType type = null; + if (this.lockinPeriodFrequencyType != null) { + type = PeriodFrequencyType.fromInt(this.lockinPeriodFrequencyType); + } + return type; + } + + public Map update(final JsonCommand command) { + + final Map actualChanges = new LinkedHashMap(10); + + final String localeAsInput = command.locale(); + + if (command.isChangeInStringParameterNamed(nameParamName, this.name)) { + final String newValue = command.stringValueOfParameterNamed(nameParamName); + actualChanges.put(nameParamName, newValue); + this.name = newValue; + } + + if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) { + final String newValue = command.stringValueOfParameterNamed(descriptionParamName); + actualChanges.put(descriptionParamName, newValue); + this.description = newValue; + } + + Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal(); + if (command.isChangeInIntegerParameterNamed(digitsAfterDecimalParamName, digitsAfterDecimal)) { + final Integer newValue = command.integerValueOfParameterNamed(digitsAfterDecimalParamName); + actualChanges.put(digitsAfterDecimalParamName, newValue); + actualChanges.put(localeParamName, localeAsInput); + digitsAfterDecimal = newValue; + this.currency = new MonetaryCurrency(this.currency.getCode(), digitsAfterDecimal); + } + + String currencyCode = this.currency.getCode(); + if (command.isChangeInStringParameterNamed(currencyCodeParamName, currencyCode)) { + final String newValue = command.stringValueOfParameterNamed(currencyCodeParamName); + actualChanges.put(currencyCodeParamName, newValue); + currencyCode = newValue; + this.currency = new MonetaryCurrency(currencyCode, this.currency.getDigitsAfterDecimal()); + } + + if (command.isChangeInBigDecimalParameterNamed(interestRateParamName, this.interestRate)) { + final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(interestRateParamName); + actualChanges.put(interestRateParamName, newValue); + actualChanges.put(localeParamName, localeAsInput); + this.interestRate = newValue; + } + + if (command.isChangeInIntegerParameterNamed(interestRatePeriodFrequencyTypeParamName, this.interestRatePeriodFrequencyType)) { + final Integer newValue = command.integerValueOfParameterNamed(interestRatePeriodFrequencyTypeParamName); + actualChanges.put(interestRatePeriodFrequencyTypeParamName, newValue); + this.interestRatePeriodFrequencyType = PeriodFrequencyType.fromInt(newValue).getValue(); + } + + if (command.isChangeInBigDecimalParameterNamed(minRequiredOpeningBalanceParamName, this.minRequiredOpeningBalance)) { + final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); + actualChanges.put(minRequiredOpeningBalanceParamName, newValue); + actualChanges.put(localeParamName, localeAsInput); + this.minRequiredOpeningBalance = newValue; + } + + if (command.isChangeInIntegerParameterNamed(lockinPeriodFrequencyParamName, this.lockinPeriodFrequency)) { + final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); + actualChanges.put(lockinPeriodFrequencyParamName, newValue); + actualChanges.put(localeParamName, localeAsInput); + this.lockinPeriodFrequency = newValue; + } + + if (command.isChangeInIntegerParameterNamed(lockinPeriodFrequencyTypeParamName, this.lockinPeriodFrequencyType)) { + final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); + actualChanges.put(lockinPeriodFrequencyTypeParamName, newValue); + this.lockinPeriodFrequencyType = PeriodFrequencyType.fromInt(newValue).getValue(); + } + + validateLockinDetails(); + + return actualChanges; + } + + private void validateLockinDetails() { + if (isInvalidConfigurationOfLockinSettings()) { throw new InvalidSavingsProductSettingsException( + "error.msg.product.savings.invalid.lockin.settings", "Invalid configuration of lock in settings.", + lockinPeriodFrequencyParamName); } + } + + private boolean isInvalidConfigurationOfLockinSettings() { + return (this.lockinPeriodFrequency == null && this.lockinPeriodFrequencyType != null) + || (this.lockinPeriodFrequencyType == null && this.lockinPeriodFrequency != null); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java new file mode 100644 index 000000000..d75bee3b5 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java @@ -0,0 +1,51 @@ +package org.mifosplatform.portfolio.savings.domain; + +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.currencyCodeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.descriptionParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.digitsAfterDecimalParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRateParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.interestRatePeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.lockinPeriodFrequencyTypeParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.minRequiredOpeningBalanceParamName; +import static org.mifosplatform.portfolio.savings.api.SavingsApiConstants.nameParamName; + +import java.math.BigDecimal; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.springframework.stereotype.Component; + +@Component +public class SavingsProductAssembler { + + public SavingsProduct assemble(final JsonCommand command) { + + final String name = command.stringValueOfParameterNamed(nameParamName); + final String description = command.stringValueOfParameterNamed(descriptionParamName); + + final String currencyCode = command.stringValueOfParameterNamed(currencyCodeParamName); + final Integer digitsAfterDecimal = command.integerValueOfParameterNamed(digitsAfterDecimalParamName); + MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal); + + final BigDecimal interestRate = command.bigDecimalValueOfParameterNamed(interestRateParamName); + PeriodFrequencyType interestRatePeriodFrequencyType = null; + final Integer interestRatePeriodFrequencyTypeValue = command.integerValueOfParameterNamed(interestRatePeriodFrequencyTypeParamName); + if (interestRatePeriodFrequencyTypeValue != null) { + interestRatePeriodFrequencyType = PeriodFrequencyType.fromInt(interestRatePeriodFrequencyTypeValue); + } + + final BigDecimal minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); + + final Integer lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); + PeriodFrequencyType lockinPeriodFrequencyType = null; + final Integer lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); + if (lockinPeriodFrequencyTypeValue != null) { + lockinPeriodFrequencyType = PeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); + } + + return SavingsProduct.createNew(name, description, currency, interestRate, interestRatePeriodFrequencyType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductRepository.java similarity index 64% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountRepository.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductRepository.java index 39a94ed3e..01896f4e1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductRepository.java @@ -3,11 +3,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; +package org.mifosplatform.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface DepositAccountRepository extends JpaRepository, JpaSpecificationExecutor { +public interface SavingsProductRepository extends JpaRepository, JpaSpecificationExecutor { // } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/InvalidSavingsProductSettingsException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/InvalidSavingsProductSettingsException.java new file mode 100644 index 000000000..831718be7 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/InvalidSavingsProductSettingsException.java @@ -0,0 +1,10 @@ +package org.mifosplatform.portfolio.savings.exception; + +import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; + +public class InvalidSavingsProductSettingsException extends AbstractPlatformDomainRuleException { + + public InvalidSavingsProductSettingsException(final String errorCode, final String defaultMessage, final String paramName) { + super(errorCode, defaultMessage, paramName); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountNotFoundException.java similarity index 52% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountNotFoundException.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountNotFoundException.java index c21b4068f..6767a7016 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountNotFoundException.java @@ -3,13 +3,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.mifosplatform.portfolio.savingsdepositaccount.exception; +package org.mifosplatform.portfolio.savings.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class DepositAccountNotFoundException extends AbstractPlatformResourceNotFoundException { +public class SavingsAccountNotFoundException extends AbstractPlatformResourceNotFoundException { - public DepositAccountNotFoundException(final Long id) { - super("error.msg.deposit.account.id.invalid", "Deposit account with identifier " + id + " does not exist", id); + public SavingsAccountNotFoundException(final Long id) { + super("error.msg.saving.account.id.invalid", "Savings account with identifier " + id + " does not exist", id); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/exception/SavingProductNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsProductNotFoundException.java similarity index 66% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/exception/SavingProductNotFoundException.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsProductNotFoundException.java index 45f5d3ec6..d2ca486c9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/exception/SavingProductNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsProductNotFoundException.java @@ -3,13 +3,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.mifosplatform.portfolio.savingsaccountproduct.exception; +package org.mifosplatform.portfolio.savings.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class SavingProductNotFoundException extends AbstractPlatformResourceNotFoundException { +public class SavingsProductNotFoundException extends AbstractPlatformResourceNotFoundException { - public SavingProductNotFoundException(final Long id) { + public SavingsProductNotFoundException(final Long id) { super("error.msg.savingproduct.id.invalid", "Saving product with identifier " + id + " does not exist", id); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsAccountCommandHandler.java new file mode 100644 index 000000000..8856c362d --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsAccountCommandHandler.java @@ -0,0 +1,26 @@ +package org.mifosplatform.portfolio.savings.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class CreateSavingsAccountCommandHandler implements NewCommandSourceHandler { + + private final SavingsAccountWritePlatformService savingAccountWritePlatformService; + + @Autowired + public CreateSavingsAccountCommandHandler(final SavingsAccountWritePlatformService savingAccountWritePlatformService) { + this.savingAccountWritePlatformService = savingAccountWritePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.savingAccountWritePlatformService.createSavingAccount(command); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsProductCommandHandler.java new file mode 100644 index 000000000..4794ebe21 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CreateSavingsProductCommandHandler.java @@ -0,0 +1,24 @@ +package org.mifosplatform.portfolio.savings.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.portfolio.savings.service.SavingsProductWritePlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class CreateSavingsProductCommandHandler implements NewCommandSourceHandler { + + private final SavingsProductWritePlatformService writePlatformService; + + @Autowired + public CreateSavingsProductCommandHandler(final SavingsProductWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } + + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.create(command); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsAccountCommandHandler.java new file mode 100644 index 000000000..d3a363ce0 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsAccountCommandHandler.java @@ -0,0 +1,27 @@ +package org.mifosplatform.portfolio.savings.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class DeleteSavingsAccountCommandHandler implements NewCommandSourceHandler { + + private final SavingsAccountWritePlatformService savingAccountWritePlatformService; + + @Autowired + public DeleteSavingsAccountCommandHandler(final SavingsAccountWritePlatformService savingAccountWritePlatformService) { + this.savingAccountWritePlatformService = savingAccountWritePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.savingAccountWritePlatformService.deleteSavingAccount(command.entityId()); + } + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/CreateSavingProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java similarity index 51% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/CreateSavingProductCommandHandler.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java index be7bd0b4e..4f42b07f1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/CreateSavingProductCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java @@ -1,24 +1,24 @@ -package org.mifosplatform.portfolio.savingsaccountproduct.handler; +package org.mifosplatform.portfolio.savings.handler; import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductWritePlatformService; +import org.mifosplatform.portfolio.savings.service.SavingsProductWritePlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class CreateSavingProductCommandHandler implements NewCommandSourceHandler { +public class DeleteSavingsProductCommandHandler implements NewCommandSourceHandler { - private final SavingProductWritePlatformService savingProductWritePlatformService; + private final SavingsProductWritePlatformService savingProductWritePlatformService; @Autowired - public CreateSavingProductCommandHandler(final SavingProductWritePlatformService savingProductWritePlatformService) { + public DeleteSavingsProductCommandHandler(final SavingsProductWritePlatformService savingProductWritePlatformService) { this.savingProductWritePlatformService = savingProductWritePlatformService; } @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingProductWritePlatformService.createSavingProduct(command); + return this.savingProductWritePlatformService.delete(command.entityId()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsAccountCommandHandler.java new file mode 100644 index 000000000..ef256c200 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsAccountCommandHandler.java @@ -0,0 +1,27 @@ +package org.mifosplatform.portfolio.savings.handler; + +import org.mifosplatform.commands.handler.NewCommandSourceHandler; +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class UpdateSavingsAccountCommandHandler implements NewCommandSourceHandler { + + private final SavingsAccountWritePlatformService savingAccountWritePlatformService; + + @Autowired + public UpdateSavingsAccountCommandHandler(final SavingsAccountWritePlatformService savingAccountWritePlatformService) { + this.savingAccountWritePlatformService = savingAccountWritePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.savingAccountWritePlatformService.updateSavingAccount(command.entityId(), command); + } + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/DeleteSavingProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java similarity index 51% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/DeleteSavingProductCommandHandler.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java index f1d6b0391..580b0e4ef 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/DeleteSavingProductCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java @@ -1,24 +1,24 @@ -package org.mifosplatform.portfolio.savingsaccountproduct.handler; +package org.mifosplatform.portfolio.savings.handler; import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductWritePlatformService; +import org.mifosplatform.portfolio.savings.service.SavingsProductWritePlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class DeleteSavingProductCommandHandler implements NewCommandSourceHandler { +public class UpdateSavingsProductCommandHandler implements NewCommandSourceHandler { - private final SavingProductWritePlatformService savingProductWritePlatformService; + private final SavingsProductWritePlatformService savingProductWritePlatformService; @Autowired - public DeleteSavingProductCommandHandler(final SavingProductWritePlatformService savingProductWritePlatformService) { + public UpdateSavingsProductCommandHandler(final SavingsProductWritePlatformService savingProductWritePlatformService) { this.savingProductWritePlatformService = savingProductWritePlatformService; } @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingProductWritePlatformService.deleteSavingProduct(command.entityId()); + return this.savingProductWritePlatformService.update(command.entityId(), command); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformService.java new file mode 100644 index 000000000..1680b6258 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformService.java @@ -0,0 +1,19 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import java.util.Collection; + +import org.mifosplatform.portfolio.savings.data.SavingsAccountData; + +public interface SavingsAccountReadPlatformService { + + Collection retrieveAll(); + + SavingsAccountData retrieveOne(Long accountId); + + SavingsAccountData retrieveTemplate(Long clientId, Long groupId, Long productId); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java new file mode 100644 index 000000000..26e9383be --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java @@ -0,0 +1,289 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.infrastructure.core.domain.JdbcSupport; +import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.organisation.monetary.data.CurrencyData; +import org.mifosplatform.portfolio.client.data.ClientData; +import org.mifosplatform.portfolio.client.service.ClientReadPlatformService; +import org.mifosplatform.portfolio.group.data.GroupData; +import org.mifosplatform.portfolio.group.service.GroupReadPlatformService; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.mifosplatform.portfolio.savings.data.SavingsAccountData; +import org.mifosplatform.portfolio.savings.data.SavingsProductData; +import org.mifosplatform.portfolio.savings.exception.SavingsAccountNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Service; + +@Service +public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountReadPlatformService { + + private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final ClientReadPlatformService clientReadPlatformService; + private final GroupReadPlatformService groupReadPlatformService; + private final SavingsProductReadPlatformService savingsProductReadPlatformService; + private final SavingsDropdownReadPlatformService dropdownReadPlatformService; + + @Autowired + public SavingsAccountReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource, + final ClientReadPlatformService clientReadPlatformService, final GroupReadPlatformService groupReadPlatformService, + final SavingsProductReadPlatformService savingProductReadPlatformService, + final SavingsDropdownReadPlatformService dropdownReadPlatformService) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.clientReadPlatformService = clientReadPlatformService; + this.groupReadPlatformService = groupReadPlatformService; + this.savingsProductReadPlatformService = savingProductReadPlatformService; + this.dropdownReadPlatformService = dropdownReadPlatformService; + } + + @Override + public Collection retrieveAll() { + + this.context.authenticatedUser(); + final SavingAccountMapper mapper = new SavingAccountMapper(); + final String sql = "select " + mapper.schema(); + return this.jdbcTemplate.query(sql, mapper, new Object[] {}); + + } + + @Override + public SavingsAccountData retrieveOne(final Long accountId) { + + try { + this.context.authenticatedUser(); + + final SavingAccountMapper mapper = new SavingAccountMapper(); + final String sql = "select " + mapper.schema() + " where sa.id = ?"; + + return this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { accountId }); + } catch (EmptyResultDataAccessException e) { + throw new SavingsAccountNotFoundException(accountId); + } + } + + private static final class SavingAccountMapper implements RowMapper { + + private final String schemaSql; + + public SavingAccountMapper() { + final StringBuilder sqlBuilder = new StringBuilder(400); + sqlBuilder.append("sa.id as id, sa.account_no as accountNo, sa.external_id as externalId, "); + sqlBuilder.append("c.id as clientId, c.display_name as clientName, "); + sqlBuilder.append("g.id as groupId, g.name as groupName, "); + sqlBuilder.append("sp.id as productId, sp.name as productName, "); + sqlBuilder.append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, "); + sqlBuilder + .append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol, "); + sqlBuilder + .append("sa.nominal_interest_rate_per_period as interestRate, sa.nominal_interest_rate_period_frequency_enum as interestRatePeriodFrequencyType, "); + sqlBuilder.append("sa.annual_nominal_interest_rate as annualInterestRate, "); + sqlBuilder.append("sa.min_required_opening_balance as minRequiredOpeningBalance, "); + sqlBuilder + .append("sa.lockin_period_frequency as lockinPeriodFrequency, sa.lockin_period_frequency_enum as lockinPeriodFrequencyType "); + sqlBuilder.append("from m_savings_account sa "); + sqlBuilder.append("left outer join m_client c ON c.id = sa.client_id "); + sqlBuilder.append("left outer join m_group g ON g.id = sa.group_id "); + sqlBuilder.append("join m_savings_product sp ON sa.product_id = sp.id "); + sqlBuilder.append("join m_currency curr on curr.code = sa.currency_code "); + + this.schemaSql = sqlBuilder.toString(); + } + + public String schema() { + return this.schemaSql; + } + + @Override + public SavingsAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + + final Long id = rs.getLong("id"); + final String accountNo = rs.getString("accountNo"); + final String externalId = rs.getString("externalId"); + + final Long groupId = rs.getLong("groupId"); + final String groupName = rs.getString("groupName"); + final Long clientId = rs.getLong("clientId"); + final String clientName = rs.getString("clientName"); + + final Long productId = rs.getLong("productId"); + final String productName = rs.getString("productName"); + + final String currencyCode = rs.getString("currencyCode"); + final String currencyName = rs.getString("currencyName"); + final String currencyNameCode = rs.getString("currencyNameCode"); + final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); + final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, + currencyNameCode); + + final BigDecimal interestRate = rs.getBigDecimal("interestRate"); + final EnumOptionData interestRatePeriodFrequencyType = SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType + .fromInt(JdbcSupport.getInteger(rs, "interestRatePeriodFrequencyType"))); + final BigDecimal annualInterestRate = rs.getBigDecimal("annualInterestRate"); + + final BigDecimal minRequiredOpeningBalance = rs.getBigDecimal("minRequiredOpeningBalance"); + + final Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency"); + EnumOptionData lockinPeriodFrequencyType = null; + final Integer lockinPeriodFrequencyTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodFrequencyType"); + if (lockinPeriodFrequencyTypeValue != null) { + lockinPeriodFrequencyType = SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType + .fromInt(lockinPeriodFrequencyTypeValue)); + } + + return SavingsAccountData.instance(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, + currency, interestRate, interestRatePeriodFrequencyType, annualInterestRate, minRequiredOpeningBalance, + lockinPeriodFrequency, lockinPeriodFrequencyType); + } + } + + @Override + public SavingsAccountData retrieveTemplate(final Long clientId, final Long groupId, final Long productId) { + + context.authenticatedUser(); + + ClientData client = null; + if (clientId != null) { + client = this.clientReadPlatformService.retrieveIndividualClient(clientId); + } + + GroupData group = null; + if (groupId != null) { + group = this.groupReadPlatformService.retrieveGroup(groupId); + } + + final Collection productOptions = this.savingsProductReadPlatformService.retrieveAllForLookup(); + SavingsAccountData template = null; + if (productId != null) { + + SavingAccountTemplateMapper mapper = new SavingAccountTemplateMapper(client, group); + + final String sql = "select " + mapper.schema() + " where sp.id = ?"; + template = this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { productId }); + + final Collection interestRatePeriodFrequencyTypeOptions = this.dropdownReadPlatformService + .retrieveInterestRatePeriodFrequencyTypeOptions(); + final Collection lockinPeriodFrequencyTypeOptions = this.dropdownReadPlatformService + .retrieveLockinPeriodFrequencyTypeOptions(); + + template = SavingsAccountData.withTemplateOptions(template, productOptions, interestRatePeriodFrequencyTypeOptions, + lockinPeriodFrequencyTypeOptions); + } else { + + String clientName = null; + if (client != null) { + clientName = client.displayName(); + } + + String groupName = null; + if (group != null) { + groupName = group.getName(); + } + + template = SavingsAccountData.withClientTemplate(clientId, clientName, groupId, groupName); + + final Collection interestRatePeriodFrequencyTypeOptions = null; + final Collection lockinPeriodFrequencyTypeOptions = null; + template = SavingsAccountData.withTemplateOptions(template, productOptions, interestRatePeriodFrequencyTypeOptions, + lockinPeriodFrequencyTypeOptions); + } + + return template; + } + + private static final class SavingAccountTemplateMapper implements RowMapper { + + private final ClientData client; + private final GroupData group; + + private final String schemaSql; + + public SavingAccountTemplateMapper(final ClientData client, final GroupData group) { + this.client = client; + this.group = group; + + final StringBuilder sqlBuilder = new StringBuilder(400); + sqlBuilder.append("sp.id as productId, sp.name as productName, "); + sqlBuilder.append("sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, "); + sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); + sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); + sqlBuilder.append("sp.nominal_interest_rate_per_period as interestRate, "); + sqlBuilder.append("sp.nominal_interest_rate_period_frequency_enum as interestRatePeriodFrequencyType, "); + sqlBuilder.append("sp.min_required_opening_balance as minRequiredOpeningBalance, "); + sqlBuilder.append("sp.lockin_period_frequency as lockinPeriodFrequency, "); + sqlBuilder.append("sp.lockin_period_frequency_enum as lockinPeriodFrequencyType "); + sqlBuilder.append("from m_savings_product sp "); + sqlBuilder.append("join m_currency curr on curr.code = sp.currency_code "); + + this.schemaSql = sqlBuilder.toString(); + } + + public String schema() { + return this.schemaSql; + } + + @Override + public SavingsAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + + final Long productId = rs.getLong("productId"); + final String productName = rs.getString("productName"); + + final String currencyCode = rs.getString("currencyCode"); + final String currencyName = rs.getString("currencyName"); + final String currencyNameCode = rs.getString("currencyNameCode"); + final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); + final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, + currencyNameCode); + + final BigDecimal interestRate = rs.getBigDecimal("interestRate"); + final EnumOptionData interestRatePeriodFrequencyType = SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType + .fromInt(JdbcSupport.getInteger(rs, "interestRatePeriodFrequencyType"))); + final BigDecimal annualInterestRate = null; + + final BigDecimal minRequiredOpeningBalance = rs.getBigDecimal("minRequiredOpeningBalance"); + + final Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency"); + EnumOptionData lockinPeriodFrequencyType = null; + final Integer lockinPeriodFrequencyTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodFrequencyType"); + if (lockinPeriodFrequencyTypeValue != null) { + lockinPeriodFrequencyType = SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType + .fromInt(lockinPeriodFrequencyTypeValue)); + } + + Long clientId = null; + String clientName = null; + if (client != null) { + clientId = client.id(); + clientName = client.displayName(); + } + + Long groupId = null; + String groupName = null; + if (group != null) { + groupId = group.getId(); + groupName = group.getName(); + } + + return SavingsAccountData.instance(null, null, null, groupId, groupName, clientId, clientName, productId, productName, + currency, interestRate, interestRatePeriodFrequencyType, annualInterestRate, minRequiredOpeningBalance, + lockinPeriodFrequency, lockinPeriodFrequencyType); + } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java new file mode 100644 index 000000000..b073a014c --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java @@ -0,0 +1,22 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; + +public interface SavingsAccountWritePlatformService { + + CommandProcessingResult createSavingAccount(JsonCommand command); + + CommandProcessingResult updateSavingAccount(Long accountId, JsonCommand command); + + CommandProcessingResult deposit(JsonCommand command); + + CommandProcessingResult withdraw(JsonCommand command); + + CommandProcessingResult deleteSavingAccount(Long accountId); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java new file mode 100644 index 000000000..ddb77b24d --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java @@ -0,0 +1,253 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; +import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.portfolio.client.domain.AccountNumberGenerator; +import org.mifosplatform.portfolio.client.domain.AccountNumberGeneratorFactory; +import org.mifosplatform.portfolio.client.domain.Client; +import org.mifosplatform.portfolio.client.domain.ClientRepository; +import org.mifosplatform.portfolio.client.exception.ClientNotFoundException; +import org.mifosplatform.portfolio.group.domain.Group; +import org.mifosplatform.portfolio.group.domain.GroupRepository; +import org.mifosplatform.portfolio.group.exception.GroupNotFoundException; +import org.mifosplatform.portfolio.savings.api.SavingsApiConstants; +import org.mifosplatform.portfolio.savings.data.SavingsAccountDataValidator; +import org.mifosplatform.portfolio.savings.domain.SavingsAccount; +import org.mifosplatform.portfolio.savings.domain.SavingsAccountAssembler; +import org.mifosplatform.portfolio.savings.domain.SavingsAccountRepository; +import org.mifosplatform.portfolio.savings.domain.SavingsProduct; +import org.mifosplatform.portfolio.savings.domain.SavingsProductRepository; +import org.mifosplatform.portfolio.savings.exception.SavingsAccountNotFoundException; +import org.mifosplatform.portfolio.savings.exception.SavingsProductNotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements SavingsAccountWritePlatformService { + + private final static Logger logger = LoggerFactory.getLogger(SavingsAccountWritePlatformServiceJpaRepositoryImpl.class); + + private final PlatformSecurityContext context; + private final SavingsAccountRepository savingAccountRepository; + private final SavingsAccountAssembler savingAccountAssembler; + private final SavingsAccountDataValidator savingsAccountDataValidator; + private final AccountNumberGeneratorFactory accountIdentifierGeneratorFactory; + private final ClientRepository clientRepository; + private final GroupRepository groupRepository; + private final SavingsProductRepository savingsProductRepository; + + @Autowired + public SavingsAccountWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, + final SavingsAccountRepository savingAccountRepository, final SavingsAccountAssembler savingAccountAssembler, + final SavingsAccountDataValidator savingsAccountDataValidator, + final AccountNumberGeneratorFactory accountIdentifierGeneratorFactory, final ClientRepository clientRepository, + final GroupRepository groupRepository, final SavingsProductRepository savingsProductRepository) { + this.context = context; + this.savingAccountRepository = savingAccountRepository; + this.savingAccountAssembler = savingAccountAssembler; + this.accountIdentifierGeneratorFactory = accountIdentifierGeneratorFactory; + this.savingsAccountDataValidator = savingsAccountDataValidator; + this.clientRepository = clientRepository; + this.groupRepository = groupRepository; + this.savingsProductRepository = savingsProductRepository; + } + + /* + * Guaranteed to throw an exception no matter what the data integrity issue + * is. + */ + private void handleDataIntegrityIssues(final JsonCommand command, final DataAccessException dve) { + + final StringBuilder errorCodeBuilder = new StringBuilder("error.msg.").append(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + + final Throwable realCause = dve.getMostSpecificCause(); + if (realCause.getMessage().contains("sa_account_no_UNIQUE")) { + final String accountNo = command.stringValueOfParameterNamed("accountNo"); + errorCodeBuilder.append(".duplicate.accountNo"); + throw new PlatformDataIntegrityException(errorCodeBuilder.toString(), "Savings account with accountNo " + accountNo + + " already exists", "accountNo", accountNo); + + } else if (realCause.getMessage().contains("sa_external_id_UNIQUE")) { + + final String externalId = command.stringValueOfParameterNamed("externalId"); + errorCodeBuilder.append(".duplicate.externalId"); + throw new PlatformDataIntegrityException(errorCodeBuilder.toString(), "Savings account with externalId " + externalId + + " already exists", "externalId", externalId); + } + + errorCodeBuilder.append(".unknown.data.integrity.issue"); + logger.error(dve.getMessage(), dve); + throw new PlatformDataIntegrityException(errorCodeBuilder.toString(), "Unknown data integrity issue with savings account."); + } + + @Transactional + @Override + public CommandProcessingResult createSavingAccount(final JsonCommand command) { + try { + this.context.authenticatedUser(); + this.savingsAccountDataValidator.validateForCreate(command.json()); + + final SavingsAccount account = this.savingAccountAssembler.assembleFrom(command); + this.savingAccountRepository.save(account); + + if (account.isAccountNumberRequiresAutoGeneration()) { + final AccountNumberGenerator accountNoGenerator = this.accountIdentifierGeneratorFactory + .determineLoanAccountNoGenerator(account.getId()); + account.updateAccountNo(accountNoGenerator.generate()); + + this.savingAccountRepository.save(account); + } + + return new CommandProcessingResultBuilder() // + .withCommandId(command.commandId()) // + .withEntityId(account.getId()) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .build(); + } catch (DataAccessException dve) { + handleDataIntegrityIssues(command, dve); + return new CommandProcessingResult(Long.valueOf(-1)); + } + + } + + @Transactional + @Override + public CommandProcessingResult updateSavingAccount(final Long accountId, final JsonCommand command) { + try { + this.context.authenticatedUser(); + this.savingsAccountDataValidator.validateForUpdate(command.json()); + + final Map changes = new LinkedHashMap(20); + + final SavingsAccount account = this.savingAccountRepository.findOne(accountId); + if (account == null) { throw new SavingsAccountNotFoundException(accountId); } + + account.update(command, changes); + + if (!changes.isEmpty()) { + + if (changes.containsKey(SavingsApiConstants.clientIdParamName)) { + final Long clientId = command.longValueOfParameterNamed(SavingsApiConstants.clientIdParamName); + if (clientId != null) { + final Client client = this.clientRepository.findOne(clientId); + if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } + account.update(client); + } else { + final Client client = null; + account.update(client); + } + } + + if (changes.containsKey(SavingsApiConstants.groupIdParamName)) { + final Long groupId = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); + if (groupId != null) { + final Group group = this.groupRepository.findOne(groupId); + if (group == null || group.isDeleted()) { throw new GroupNotFoundException(groupId); } + account.update(group); + } else { + final Group group = null; + account.update(group); + } + } + + if (changes.containsKey(SavingsApiConstants.productIdParamName)) { + final Long productId = command.longValueOfParameterNamed(SavingsApiConstants.productIdParamName); + final SavingsProduct product = this.savingsProductRepository.findOne(productId); + if (product == null) { throw new SavingsProductNotFoundException(productId); } + + account.update(product); + } + + this.savingAccountRepository.saveAndFlush(account); + } + + return new CommandProcessingResultBuilder() // + .withCommandId(command.commandId()) // + .withEntityId(account.getId()) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .with(changes) // + .build(); + } catch (DataAccessException dve) { + handleDataIntegrityIssues(command, dve); + return new CommandProcessingResult(Long.valueOf(-1)); + } + } + + @Transactional + @Override + public CommandProcessingResult deposit(final JsonCommand command) { + + this.context.authenticatedUser(); + + SavingsAccount account = this.savingAccountRepository.findOne(command.entityId()); + if (account == null) { throw new SavingsAccountNotFoundException(command.entityId()); } + + // FIXME - add basic support for deposits + + return new CommandProcessingResultBuilder() // + .withEntityId(account.getId()) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .build(); + } + + @Transactional + @Override + public CommandProcessingResult withdraw(final JsonCommand command) { + + this.context.authenticatedUser(); + + final SavingsAccount account = this.savingAccountRepository.findOne(command.entityId()); + if (account == null) { throw new SavingsAccountNotFoundException(command.entityId()); } + + // FIXME - add basic support for withdrawals + + this.savingAccountRepository.save(account); + + return new CommandProcessingResultBuilder() // + .withEntityId(account.getId()) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .build(); + } + + @Transactional + @Override + public CommandProcessingResult deleteSavingAccount(final Long accountId) { + + this.context.authenticatedUser(); + + final SavingsAccount account = this.savingAccountRepository.findOne(accountId); + if (account == null) { throw new SavingsAccountNotFoundException(accountId); } + + this.savingAccountRepository.delete(account); + + return new CommandProcessingResultBuilder() // + .withEntityId(accountId) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .build(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformService.java new file mode 100644 index 000000000..a55d20bde --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformService.java @@ -0,0 +1,12 @@ +package org.mifosplatform.portfolio.savings.service; + +import java.util.Collection; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; + +public interface SavingsDropdownReadPlatformService { + + Collection retrieveInterestRatePeriodFrequencyTypeOptions(); + + Collection retrieveLockinPeriodFrequencyTypeOptions(); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java new file mode 100644 index 000000000..8b372cad6 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java @@ -0,0 +1,34 @@ +package org.mifosplatform.portfolio.savings.service; + +import java.util.Arrays; +import java.util.List; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.springframework.stereotype.Service; + +@Service +public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownReadPlatformService { + + @Override + public List retrieveInterestRatePeriodFrequencyTypeOptions() { + List allowedInterestRatePeriodFrequencyTypeOptions = Arrays.asList( // + SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType.MONTHS), // + SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType.YEARS) // + ); + + return allowedInterestRatePeriodFrequencyTypeOptions; + } + + @Override + public List retrieveLockinPeriodFrequencyTypeOptions() { + List allowedLockinPeriodFrequencyTypeOptions = Arrays.asList( // + SavingsEnumerations.lockinPeriodFrequencyType(PeriodFrequencyType.DAYS), // + SavingsEnumerations.lockinPeriodFrequencyType(PeriodFrequencyType.WEEKS), // + SavingsEnumerations.lockinPeriodFrequencyType(PeriodFrequencyType.MONTHS), // + SavingsEnumerations.lockinPeriodFrequencyType(PeriodFrequencyType.YEARS) // + ); + + return allowedLockinPeriodFrequencyTypeOptions; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsEnumerations.java new file mode 100644 index 000000000..d091b5e17 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsEnumerations.java @@ -0,0 +1,74 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; + +public class SavingsEnumerations { + + public static EnumOptionData interestRatePeriodFrequencyType(final int id) { + return interestRatePeriodFrequencyType(PeriodFrequencyType.fromInt(id)); + } + + public static EnumOptionData interestRatePeriodFrequencyType(final PeriodFrequencyType type) { + final String codePrefix = "savings.interest.rate."; + EnumOptionData optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), + PeriodFrequencyType.INVALID.getCode(), "Invalid"); + switch (type) { + case INVALID: + break; + case DAYS: + optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix + + PeriodFrequencyType.DAYS.getCode(), "Per day"); + break; + case WEEKS: + optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix + + PeriodFrequencyType.WEEKS.getCode(), "Per week"); + break; + case MONTHS: + optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix + + PeriodFrequencyType.MONTHS.getCode(), "Per month"); + break; + case YEARS: + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), codePrefix + + PeriodFrequencyType.YEARS.getCode(), "Per year"); + break; + } + return optionData; + } + + public static EnumOptionData lockinPeriodFrequencyType(final int id) { + return lockinPeriodFrequencyType(PeriodFrequencyType.fromInt(id)); + } + + public static EnumOptionData lockinPeriodFrequencyType(final PeriodFrequencyType type) { + final String codePrefix = "savings.lockin."; + EnumOptionData optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), + PeriodFrequencyType.INVALID.getCode(), "Invalid"); + switch (type) { + case INVALID: + break; + case DAYS: + optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix + + PeriodFrequencyType.DAYS.getCode(), "Days"); + break; + case WEEKS: + optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix + + PeriodFrequencyType.WEEKS.getCode(), "Weeks"); + break; + case MONTHS: + optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix + + PeriodFrequencyType.MONTHS.getCode(), "Months"); + break; + case YEARS: + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), codePrefix + + PeriodFrequencyType.YEARS.getCode(), "Years"); + break; + } + return optionData; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformService.java new file mode 100644 index 000000000..538c943e5 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformService.java @@ -0,0 +1,20 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import java.util.Collection; + +import org.mifosplatform.portfolio.savings.data.SavingsProductData; + +public interface SavingsProductReadPlatformService { + + Collection retrieveAll(); + + Collection retrieveAllForLookup(); + + SavingsProductData retrieveOne(Long productId); + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java new file mode 100644 index 000000000..0a229a906 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java @@ -0,0 +1,132 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; + +import org.mifosplatform.infrastructure.core.data.EnumOptionData; +import org.mifosplatform.infrastructure.core.domain.JdbcSupport; +import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.organisation.monetary.data.CurrencyData; +import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; +import org.mifosplatform.portfolio.savings.data.SavingsProductData; +import org.mifosplatform.portfolio.savings.exception.SavingsProductNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Service; + +@Service +public class SavingsProductReadPlatformServiceImpl implements SavingsProductReadPlatformService { + + private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final SavingProductMapper savingsProductRowMapper = new SavingProductMapper(); + private final SavingProductLookupMapper savingsProductLookupsRowMapper = new SavingProductLookupMapper(); + + @Autowired + public SavingsProductReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) { + this.context = context; + jdbcTemplate = new JdbcTemplate(dataSource); + } + + @Override + public Collection retrieveAll() { + + this.context.authenticatedUser(); + + final String sql = "select " + savingsProductRowMapper.schema(); + + return this.jdbcTemplate.query(sql, savingsProductRowMapper); + } + + @Override + public Collection retrieveAllForLookup() { + + final String sql = "select " + savingsProductLookupsRowMapper.schema(); + + return this.jdbcTemplate.query(sql, savingsProductLookupsRowMapper); + } + + @Override + public SavingsProductData retrieveOne(final Long savingProductId) { + try { + this.context.authenticatedUser(); + final String sql = "select " + savingsProductRowMapper.schema() + " where sp.id = ?"; + return this.jdbcTemplate.queryForObject(sql, savingsProductRowMapper, new Object[] { savingProductId }); + } catch (EmptyResultDataAccessException e) { + throw new SavingsProductNotFoundException(savingProductId); + } + } + + private static final class SavingProductMapper implements RowMapper { + + public String schema() { + return "sp.id as id,sp.name as name, sp.description as description, " + + "sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, " + + "curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol, " + + "sp.nominal_interest_rate_per_period as interestRate, sp.nominal_interest_rate_period_frequency_enum as interestRatePeriodFrequencyType, " + + "sp.min_required_opening_balance as minRequiredOpeningBalance, " + + "sp.lockin_period_frequency as lockinPeriodFrequency, sp.lockin_period_frequency_enum as lockinPeriodFrequencyType " // + + "from m_savings_product sp " // + + "join m_currency curr on curr.code = sp.currency_code"; + } + + @Override + public SavingsProductData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + + Long id = rs.getLong("id"); + String name = rs.getString("name"); + String description = rs.getString("description"); + + String currencyCode = rs.getString("currencyCode"); + String currencyName = rs.getString("currencyName"); + String currencyNameCode = rs.getString("currencyNameCode"); + String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); + Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); + + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, + currencyNameCode); + BigDecimal interestRate = rs.getBigDecimal("interestRate"); + EnumOptionData interestRatePeriodFrequencyType = SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType + .fromInt(JdbcSupport.getInteger(rs, "interestRatePeriodFrequencyType"))); + + final BigDecimal minRequiredOpeningBalance = rs.getBigDecimal("minRequiredOpeningBalance"); + + Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency"); + EnumOptionData lockinPeriodFrequencyType = null; + final Integer lockinPeriodFrequencyTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodFrequencyType"); + if (lockinPeriodFrequencyTypeValue != null) { + lockinPeriodFrequencyType = SavingsEnumerations.interestRatePeriodFrequencyType(PeriodFrequencyType + .fromInt(lockinPeriodFrequencyTypeValue)); + } + + return SavingsProductData.instance(id, name, description, currency, interestRate, interestRatePeriodFrequencyType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType); + } + } + + private static final class SavingProductLookupMapper implements RowMapper { + + public String schema() { + return " sp.id as id, sp.name as name from m_savings_product sp"; + } + + @Override + public SavingsProductData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + + final Long id = rs.getLong("id"); + final String name = rs.getString("name"); + + return SavingsProductData.lookup(id, name); + } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformService.java similarity index 50% rename from mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformService.java rename to mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformService.java index e4eab781c..f276067a0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformService.java @@ -3,16 +3,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.mifosplatform.portfolio.savingsaccountproduct.service; +package org.mifosplatform.portfolio.savings.service; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -public interface SavingProductWritePlatformService { +public interface SavingsProductWritePlatformService { - CommandProcessingResult createSavingProduct(JsonCommand command); + CommandProcessingResult create(JsonCommand command); - CommandProcessingResult updateSavingProduct(Long productId, JsonCommand command); + CommandProcessingResult update(Long productId, JsonCommand command); - CommandProcessingResult deleteSavingProduct(Long productId); + CommandProcessingResult delete(Long productId); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java new file mode 100644 index 000000000..ad5dc062c --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java @@ -0,0 +1,131 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.mifosplatform.portfolio.savings.service; + +import java.util.Map; + +import org.mifosplatform.infrastructure.core.api.JsonCommand; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; +import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; +import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.portfolio.savings.data.SavingsProductDataValidator; +import org.mifosplatform.portfolio.savings.domain.SavingsProduct; +import org.mifosplatform.portfolio.savings.domain.SavingsProductAssembler; +import org.mifosplatform.portfolio.savings.domain.SavingsProductRepository; +import org.mifosplatform.portfolio.savings.exception.SavingsProductNotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements SavingsProductWritePlatformService { + + private final Logger logger; + private final PlatformSecurityContext context; + private final SavingsProductRepository savingProductRepository; + private final SavingsProductDataValidator fromApiJsonDataValidator; + private final SavingsProductAssembler savingsProductAssembler; + + @Autowired + public SavingsProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, + final SavingsProductRepository savingProductRepository, final SavingsProductDataValidator fromApiJsonDataValidator, + final SavingsProductAssembler savingsProductAssembler) { + this.context = context; + this.savingProductRepository = savingProductRepository; + this.fromApiJsonDataValidator = fromApiJsonDataValidator; + this.savingsProductAssembler = savingsProductAssembler; + this.logger = LoggerFactory.getLogger(SavingsProductWritePlatformServiceJpaRepositoryImpl.class); + } + + /* + * Guaranteed to throw an exception no matter what the data integrity issue + * is. + */ + private void handleDataIntegrityIssues(final JsonCommand command, final DataAccessException dae) { + + final Throwable realCause = dae.getMostSpecificCause(); + if (realCause.getMessage().contains("sp_unq_name")) { + + final String name = command.stringValueOfParameterNamed("name"); + throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.name", "Savings product with name `" + name + + "` already exists", "name", name); + } + + logAsErrorUnexpectedDataIntegrityException(dae); + throw new PlatformDataIntegrityException("error.msg.savingsproduct.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } + + private void logAsErrorUnexpectedDataIntegrityException(final DataAccessException dae) { + logger.error(dae.getMessage(), dae); + } + + @Transactional + @Override + public CommandProcessingResult create(final JsonCommand command) { + + try { + this.context.authenticatedUser(); + + this.fromApiJsonDataValidator.validateForCreate(command.json()); + + final SavingsProduct product = this.savingsProductAssembler.assemble(command); + + this.savingProductRepository.save(product); + + return new CommandProcessingResultBuilder() // + .withEntityId(product.getId()) // + .build(); + } catch (DataAccessException e) { + handleDataIntegrityIssues(command, e); + return CommandProcessingResult.empty(); + } + } + + @Transactional + @Override + public CommandProcessingResult update(final Long productId, final JsonCommand command) { + + try { + this.context.authenticatedUser(); + this.fromApiJsonDataValidator.validateForUpdate(command.json()); + + final SavingsProduct product = this.savingProductRepository.findOne(productId); + if (product == null) { throw new SavingsProductNotFoundException(productId); } + + final Map changes = product.update(command); + if (!changes.isEmpty()) { + this.savingProductRepository.saveAndFlush(product); + } + + return new CommandProcessingResultBuilder() // + .withEntityId(product.getId()) // + .with(changes).build(); + } catch (DataAccessException e) { + handleDataIntegrityIssues(command, e); + return CommandProcessingResult.empty(); + } + } + + @Transactional + @Override + public CommandProcessingResult delete(final Long productId) { + + this.context.authenticatedUser(); + final SavingsProduct product = this.savingProductRepository.findOne(productId); + if (product == null) { throw new SavingsProductNotFoundException(productId); } + + this.savingProductRepository.delete(product); + + return new CommandProcessingResultBuilder() // + .withEntityId(product.getId()) // + .build(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/api/SavingsAccountApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/api/SavingsAccountApiResource.java deleted file mode 100644 index c9f3d0f08..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/api/SavingsAccountApiResource.java +++ /dev/null @@ -1,330 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.api; - -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriInfo; - -import org.apache.commons.lang.StringUtils; -import org.mifosplatform.commands.domain.CommandWrapper; -import org.mifosplatform.commands.service.CommandWrapperBuilder; -import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; -import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; -import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; -import org.mifosplatform.infrastructure.core.api.JsonQuery; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; -import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; -import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.organisation.monetary.service.CurrencyReadPlatformService; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountForLookup; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountTransactionsData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingPermissionData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; -import org.mifosplatform.portfolio.savingsaccount.service.CalculateSavingSchedule; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountReadPlatformService; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductLookup; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsLockinPeriodEnum; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductEnumerations; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductReadPlatformService; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; - -@Path("/savingaccounts") -@Component -@Scope("singleton") -public class SavingsAccountApiResource { - - private final Set SAVINGS_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "status", "externalId", - "clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod", - "savingsFrequencyType", "totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType", - "interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", "actualCommencementDate", "maturesOnDate", - "projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount", - "outstandingAmount", "preClosureAllowed", "preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", - "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "productOptions", "currencyOptions", "savingsProductTypeOptions", - "tenureTypeOptions", "savingFrequencyOptions", "savingsInterestTypeOptions", "lockinPeriodTypeOptions", - "interestCalculationOptions", "permissions", "savingScheduleDatas", "dueAmount", "savingScheduleData", "transactions", - "interestPostEvery", "interestPostFrequency")); - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - private final SavingAccountReadPlatformService savingAccountReadPlatformService; - private final SavingProductReadPlatformService savingProductReadPlatformService; - private final CurrencyReadPlatformService currencyReadPlatformService; - private final String entityType = "SAVINGSACCOUNT"; - private final PlatformSecurityContext context; - private final CalculateSavingSchedule calculateSavingSchedule; - private final ToApiJsonSerializer toApiJsonSerializer; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private final FromJsonHelper fromJsonHelper; - private final DefaultToApiJsonSerializer savingScheduleToApiJsonSerializer; - - @Autowired - public SavingsAccountApiResource(final SavingAccountWritePlatformService savingAccountWritePlatformService, - final SavingAccountReadPlatformService savingAccountReadPlatformService, - final SavingProductReadPlatformService savingProductReadPlatformService, - final CurrencyReadPlatformService currencyReadPlatformService, final PlatformSecurityContext context, - final CalculateSavingSchedule calculateSavingSchedule, final ToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final FromJsonHelper fromJsonHelper, - final DefaultToApiJsonSerializer savingScheduleToApiJsonSerializer) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - this.savingAccountReadPlatformService = savingAccountReadPlatformService; - this.savingProductReadPlatformService = savingProductReadPlatformService; - this.currencyReadPlatformService = currencyReadPlatformService; - this.context = context; - this.calculateSavingSchedule = calculateSavingSchedule; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.fromJsonHelper = fromJsonHelper; - this.savingScheduleToApiJsonSerializer = savingScheduleToApiJsonSerializer; - } - - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String createSavingAccount(@QueryParam("command") final String commandParam, @Context final UriInfo uriInfo, - final String apiRequestBodyAsJson) { - - if (is(commandParam, "calculateSavingSchedule")) { - - final JsonElement parsedQuery = this.fromJsonHelper.parse(apiRequestBodyAsJson); - final JsonQuery query = JsonQuery.from(apiRequestBodyAsJson, parsedQuery, this.fromJsonHelper); - - SavingScheduleData savingSchedule = this.calculateSavingSchedule.calculateSavingSchedule(query); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - return this.savingScheduleToApiJsonSerializer.serialize(settings, savingSchedule, new HashSet()); - - } - - final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingAccount().withJson(apiRequestBodyAsJson).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - - } - - @PUT - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateSavingAccount(@PathParam("accountId") final Long accountId, final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSavingAccount(accountId).withJson(apiRequestBodyAsJson) - .build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - } - - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAllDepositAccounts(@Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - Collection accounts = this.savingAccountReadPlatformService.retrieveAllSavingsAccounts(); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - return this.toApiJsonSerializer.serialize(settings, accounts, SAVINGS_ACCOUNTS_DATA_PARAMETERS); - } - - @GET - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveDepositAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - SavingPermissionData permissions = null; - SavingScheduleData savingScheduleData = null; - Collection transactions = null; - - SavingAccountData account = this.savingAccountReadPlatformService.retrieveSavingsAccount(accountId); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - if (settings.isTemplate()) { - account = handleTemplateRelatedData(account); - } - - Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); - if (!associationParameters.isEmpty()) { - if (associationParameters.contains("all")) { - associationParameters.addAll(Arrays.asList("savingScheduleData", "transactions")); - } - - if (associationParameters.contains("savingScheduleData")) { - CurrencyData currencyData = account.getCurrencyData(); - savingScheduleData = this.savingAccountReadPlatformService.retrieveSavingsAccountSchedule(accountId, currencyData); - account = new SavingAccountData(account, savingScheduleData); - } - if (associationParameters.contains("transactions")) { - transactions = this.savingAccountReadPlatformService.retrieveSavingsAccountTransactions(accountId); - account = new SavingAccountData(account, transactions); - } - permissions = this.savingAccountReadPlatformService.retrieveSavingAccountPermissions(account); - account = new SavingAccountData(account, permissions); - } - - return this.toApiJsonSerializer.serialize(settings, account, SAVINGS_ACCOUNTS_DATA_PARAMETERS); - } - - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveNewDepositAccountDetails(@QueryParam("clientId") final Long clientId, - @QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - SavingAccountData account = this.savingAccountReadPlatformService.retrieveNewSavingsAccountDetails(clientId, productId); - account = handleTemplateRelatedData(account); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, account, SAVINGS_ACCOUNTS_DATA_PARAMETERS); - } - - private SavingAccountData handleTemplateRelatedData(final SavingAccountData account) { - - Collection productOptions = savingProductReadPlatformService.retrieveAllSavingProductsForLookup(); - Collection currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); - - EnumOptionData recurring = SavingProductEnumerations.savingProductType(SavingProductType.RECURRING); - EnumOptionData regular = SavingProductEnumerations.savingProductType(SavingProductType.REGULAR); - List savingsProductTypeOptions = Arrays.asList(recurring, regular); - - EnumOptionData fixed = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD); - EnumOptionData perpetual = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.PERPETUAL); - List tenureTypeOptions = Arrays.asList(fixed, perpetual); - - EnumOptionData monthly = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY); - List savingFrequencyOptions = Arrays.asList(monthly); - - EnumOptionData simple = SavingProductEnumerations.savingInterestType(SavingsInterestType.SIMPLE); - EnumOptionData compounding = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING); - List savingsInterestTypeOptions = Arrays.asList(simple, compounding); - - EnumOptionData months = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS); - List lockinPeriodTypeOptions = Arrays.asList(months); - - EnumOptionData averagebal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL); - // EnumOptionData minbal = - // SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MINBAL); - EnumOptionData monthlyCollection = SavingProductEnumerations - .savingInterestCalculationMethod(SavingInterestCalculationMethod.MONTHLYCOLLECTION); - List interestCalculationOptions = Arrays.asList(averagebal, monthlyCollection); - BigDecimal dueAmount = this.savingAccountReadPlatformService.deriveSavingDueAmount(account); - return new SavingAccountData(account, productOptions, currencyOptions, savingsProductTypeOptions, tenureTypeOptions, - savingFrequencyOptions, savingsInterestTypeOptions, lockinPeriodTypeOptions, interestCalculationOptions, dueAmount); - } - - private boolean is(final String commandParam, final String commandValue) { - return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); - } - - @POST - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String savingStateTransitions(@PathParam("accountId") final Long accountId, @QueryParam("command") final String commandParam, - final String apiRequestBodyAsJson) { - - CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); - CommandProcessingResult result = null; - - if (is(commandParam, "approve")) { - final CommandWrapper commandRequest = builder.approveSavingAccountApplication(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "depositmoney")) { - final CommandWrapper commandRequest = builder.depositOfSavingAmount(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "withdraw")) { - final CommandWrapper commandRequest = builder.withdrawSavingAmount(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "reject")) { - final CommandWrapper commandRequest = builder.rejectSavingApplication(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "withdrewbyclient")) { - final CommandWrapper commandRequest = builder.withdrawSavingApplication(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "undoapproval")) { - final CommandWrapper commandRequest = builder.undoApprovalOfSavingApplication(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else { - throw new UnrecognizedQueryParamException("command", commandParam); - } - - return this.toApiJsonSerializer.serialize(result); - } - - @DELETE - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String deleteSavingAccount(@PathParam("accountId") final Long accountId) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingAccount(accountId).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - - } - - @POST - @Path("postinterest") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String postInterest() { - - Collection savingAccounts = this.savingAccountReadPlatformService.retrieveSavingAccountsForLookUp(); - CommandProcessingResult entityIdentifier = this.savingAccountWritePlatformService.postInterest(savingAccounts); - return this.toApiJsonSerializer.serialize(entityIdentifier); - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountData.java deleted file mode 100644 index d2732f31a..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountData.java +++ /dev/null @@ -1,511 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.data; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductLookup; - -/** - * Immutable data object representing a savings account. - */ -public class SavingAccountData { - - private final Long id; - private final EnumOptionData status; - private final String externalId; - private final Long clientId; - private final String clientName; - private final Long productId; - private final String productName; - private final EnumOptionData productType; - private final CurrencyData currencyData; - private final BigDecimal savingsDepositAmountPerPeriod; - private final EnumOptionData savingsFrequencyType; - private final BigDecimal totalDepositAmount; - private final BigDecimal recurringInterestRate; - private final BigDecimal savingInterestRate; - private final EnumOptionData interestType; - private final EnumOptionData interestCalculationMethod; - private final Integer tenure; - private final EnumOptionData tenureType; - private final LocalDate projectedCommencementDate; - private final LocalDate actualCommencementDate; - private final LocalDate maturesOnDate; - private final BigDecimal projectedInterestAccuredOnMaturity; - private final BigDecimal actualInterestAccured; - private final BigDecimal projectedMaturityAmount; - private final BigDecimal actualMaturityAmount; - private final boolean preClosureAllowed; - private final BigDecimal preClosureInterestRate; - private final LocalDate withdrawnonDate; - private final LocalDate rejectedonDate; - private final LocalDate closedonDate; - private final boolean isLockinPeriodAllowed; - private final Integer lockinPeriod; - private final EnumOptionData lockinPeriodType; - private final Integer depositEvery; - - private final List productOptions; - private final Collection currencyOptions; - private final List savingsProductTypeOptions; - private final List tenureTypeOptions; - private final List savingFrequencyOptions; - private final List savingsInterestTypeOptions; - private final List lockinPeriodTypeOptions; - private final List interestCalculationOptions; - - private final Collection savingScheduleDatas; - private final SavingPermissionData permissions; - private final BigDecimal outstandingAmount; - private final BigDecimal dueAmount; - private final SavingScheduleData savingScheduleData; - private final Collection transactions; - - private final Integer interestPostEvery; - private final EnumOptionData interestPostFrequency; - - public static SavingAccountData createFrom(final Long clientId, final String clientDisplayName) { - return new SavingAccountData(clientId, clientDisplayName); - } - - public SavingAccountData(final Long id, final EnumOptionData status, final String externalId, final Long clientId, - final String clientName, final Long productId, final String productName, final EnumOptionData productType, - final CurrencyData currencyData, final BigDecimal savingsDepositAmountPerPeriod, final EnumOptionData savingsFrequencyType, - final BigDecimal totalDepositAmount, final BigDecimal recurringInterestRate, final BigDecimal savingInterestRate, - final EnumOptionData interestType, final EnumOptionData interestCalculationMethod, final Integer tenure, - final EnumOptionData tenureType, final LocalDate projectedCommencementDate, final LocalDate actualCommencementDate, - final LocalDate maturesOnDate, final BigDecimal projectedInterestAccuredOnMaturity, final BigDecimal actualInterestAccured, - final BigDecimal projectedMaturityAmount, final BigDecimal actualMaturityAmount, final boolean preClosureAllowed, - final BigDecimal preClosureInterestRate, final LocalDate withdrawnonDate, final LocalDate rejectedonDate, - final LocalDate closedonDate, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, - final EnumOptionData lockinPeriodType, final Integer depositEvery, final BigDecimal outstandingAmount, - final Integer interestPostEvery, final EnumOptionData interestPostFrequency) { - this.id = id; - this.status = status; - this.externalId = externalId; - this.clientId = clientId; - this.clientName = clientName; - this.productId = productId; - this.productName = productName; - this.productType = productType; - this.currencyData = currencyData; - this.savingsDepositAmountPerPeriod = savingsDepositAmountPerPeriod; - this.savingsFrequencyType = savingsFrequencyType; - this.totalDepositAmount = totalDepositAmount; - this.recurringInterestRate = recurringInterestRate; - this.savingInterestRate = savingInterestRate; - this.interestType = interestType; - this.interestCalculationMethod = interestCalculationMethod; - this.tenure = tenure; - this.tenureType = tenureType; - this.projectedCommencementDate = projectedCommencementDate; - this.actualCommencementDate = actualCommencementDate; - this.maturesOnDate = maturesOnDate; - this.projectedInterestAccuredOnMaturity = projectedInterestAccuredOnMaturity; - this.actualInterestAccured = actualInterestAccured; - this.projectedMaturityAmount = projectedMaturityAmount; - this.actualMaturityAmount = actualMaturityAmount; - this.preClosureAllowed = preClosureAllowed; - this.preClosureInterestRate = preClosureInterestRate; - this.withdrawnonDate = withdrawnonDate; - this.rejectedonDate = rejectedonDate; - this.closedonDate = closedonDate; - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - this.depositEvery = depositEvery; - this.productOptions = new ArrayList(); - this.currencyOptions = null; - this.savingsProductTypeOptions = null; - this.tenureTypeOptions = null; - this.savingFrequencyOptions = null; - this.savingsInterestTypeOptions = null; - this.lockinPeriodTypeOptions = null; - this.interestCalculationOptions = null; - this.savingScheduleDatas = null; - this.permissions = null; - this.outstandingAmount = outstandingAmount; - this.dueAmount = BigDecimal.ZERO; - this.savingScheduleData = null; - this.transactions = null; - this.interestPostEvery = interestPostEvery; - this.interestPostFrequency = interestPostFrequency; - } - - public SavingAccountData(final Long clientId, final String clientName) { - this.id = null; - this.status = null; - this.externalId = null; - this.clientId = clientId; - this.clientName = clientName; - this.productId = null; - this.productName = null; - this.productType = null; - this.currencyData = new CurrencyData("USD", "US Dollar", 2, "$", "currency.USD"); - this.savingsDepositAmountPerPeriod = null; - this.savingsFrequencyType = null; - this.totalDepositAmount = null; - this.recurringInterestRate = null; - this.savingInterestRate = null; - this.interestType = null; - this.interestCalculationMethod = null; - this.tenure = null; - this.tenureType = null; - this.projectedCommencementDate = null; - this.actualCommencementDate = null; - this.maturesOnDate = null; - this.projectedInterestAccuredOnMaturity = null; - this.actualInterestAccured = null; - this.projectedMaturityAmount = null; - this.actualMaturityAmount = null; - this.preClosureAllowed = false; - this.preClosureInterestRate = null; - this.withdrawnonDate = null; - this.rejectedonDate = null; - this.closedonDate = null; - this.isLockinPeriodAllowed = false; - this.lockinPeriod = null; - this.lockinPeriodType = null; - this.depositEvery = null; - this.productOptions = new ArrayList(); - this.currencyOptions = null; - this.savingsProductTypeOptions = null; - this.tenureTypeOptions = null; - this.savingFrequencyOptions = null; - this.savingsInterestTypeOptions = null; - this.lockinPeriodTypeOptions = null; - this.interestCalculationOptions = null; - this.savingScheduleDatas = null; - this.permissions = null; - this.outstandingAmount = BigDecimal.ZERO; - this.dueAmount = BigDecimal.ZERO; - this.savingScheduleData = null; - this.transactions = null; - this.interestPostEvery = null; - this.interestPostFrequency = null; - } - - public SavingAccountData(final SavingAccountData account, final Collection productOptions, - final Collection currencyOptions, final List savingsProductTypeOptions, - final List tenureTypeOptions, final List savingFrequencyOptions, - final List savingsInterestTypeOptions, final List lockinPeriodTypeOptions, - final List interestCalculationOptions, final BigDecimal dueAmount) { - this.id = account.id; - this.status = account.status; - this.externalId = account.externalId; - this.clientId = account.clientId; - this.clientName = account.clientName; - this.productId = account.productId; - this.productName = account.productName; - this.productType = account.productType; - this.currencyData = account.currencyData; - this.savingsDepositAmountPerPeriod = account.savingsDepositAmountPerPeriod; - this.savingsFrequencyType = account.savingsFrequencyType; - this.totalDepositAmount = account.totalDepositAmount; - this.recurringInterestRate = account.recurringInterestRate; - this.savingInterestRate = account.savingInterestRate; - this.interestType = account.interestType; - this.interestCalculationMethod = account.interestCalculationMethod; - this.tenure = account.tenure; - this.tenureType = account.tenureType; - this.projectedCommencementDate = account.projectedCommencementDate; - this.actualCommencementDate = account.actualCommencementDate; - this.maturesOnDate = account.maturesOnDate; - this.projectedInterestAccuredOnMaturity = account.projectedInterestAccuredOnMaturity; - this.actualInterestAccured = account.actualInterestAccured; - this.projectedMaturityAmount = account.projectedMaturityAmount; - this.actualMaturityAmount = account.actualMaturityAmount; - this.preClosureAllowed = account.preClosureAllowed; - this.preClosureInterestRate = account.preClosureInterestRate; - this.withdrawnonDate = account.withdrawnonDate; - this.rejectedonDate = account.rejectedonDate; - this.closedonDate = account.closedonDate; - this.isLockinPeriodAllowed = account.isLockinPeriodAllowed; - this.lockinPeriod = account.lockinPeriod; - this.lockinPeriodType = account.lockinPeriodType; - this.depositEvery = account.depositEvery; - - this.productOptions = (List) productOptions; - this.currencyOptions = currencyOptions; - this.savingsProductTypeOptions = savingsProductTypeOptions; - this.tenureTypeOptions = tenureTypeOptions; - this.savingFrequencyOptions = savingFrequencyOptions; - this.savingsInterestTypeOptions = savingsInterestTypeOptions; - this.lockinPeriodTypeOptions = lockinPeriodTypeOptions; - this.interestCalculationOptions = interestCalculationOptions; - this.dueAmount = dueAmount; - - this.savingScheduleDatas = account.savingScheduleDatas; - this.permissions = account.permissions; - this.outstandingAmount = account.outstandingAmount; - this.savingScheduleData = account.savingScheduleData; - this.transactions = account.transactions; - this.interestPostEvery = account.interestPostEvery; - this.interestPostFrequency = account.interestPostFrequency; - } - - public SavingAccountData(final Long clientId, final String clientName, final Long productId, final String productName, - final CurrencyData currency, final BigDecimal interestRate, final BigDecimal savingsDepositAmountPerPeriod, - final EnumOptionData productType, final EnumOptionData tenureType, final Integer tenure, - final EnumOptionData savingsFrequencyType, final EnumOptionData interestType, final EnumOptionData interestCalculationMethod, - final boolean lockinPeriodAllowed, final Integer lockinPeriod, final EnumOptionData lockinPeriodType, final Integer depositEvery) { - this.id = null; - this.status = null; - this.externalId = null; - this.clientId = clientId; - this.clientName = clientName; - this.productId = productId; - this.productName = productName; - this.productType = productType; - this.currencyData = currency; - this.savingsDepositAmountPerPeriod = savingsDepositAmountPerPeriod; - this.savingsFrequencyType = savingsFrequencyType; - this.totalDepositAmount = null; - this.recurringInterestRate = interestRate; - this.savingInterestRate = interestRate; - this.interestType = interestType; - this.interestCalculationMethod = interestCalculationMethod; - this.tenure = tenure; - this.tenureType = tenureType; - this.projectedCommencementDate = new LocalDate(); - this.actualCommencementDate = null; - this.maturesOnDate = null; - this.projectedInterestAccuredOnMaturity = null; - this.actualInterestAccured = null; - this.projectedMaturityAmount = null; - this.actualMaturityAmount = null; - this.preClosureAllowed = true; - this.preClosureInterestRate = null; - this.withdrawnonDate = null; - this.rejectedonDate = null; - this.closedonDate = null; - this.isLockinPeriodAllowed = lockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - this.depositEvery = depositEvery; - this.productOptions = null; - this.currencyOptions = null; - this.savingsProductTypeOptions = null; - this.tenureTypeOptions = null; - this.savingFrequencyOptions = null; - this.savingsInterestTypeOptions = null; - this.lockinPeriodTypeOptions = null; - this.interestCalculationOptions = null; - this.savingScheduleDatas = null; - this.permissions = null; - this.outstandingAmount = BigDecimal.ZERO; - this.dueAmount = BigDecimal.ZERO; - this.savingScheduleData = null; - this.transactions = null; - this.interestPostEvery = 3; - this.interestPostFrequency = savingsFrequencyType; - } - - public SavingAccountData(final SavingAccountData account, final SavingPermissionData permissions) { - this.id = account.id; - this.status = account.status; - this.externalId = account.externalId; - this.clientId = account.clientId; - this.clientName = account.clientName; - this.productId = account.productId; - this.productName = account.productName; - this.productType = account.productType; - this.currencyData = account.currencyData; - this.savingsDepositAmountPerPeriod = account.savingsDepositAmountPerPeriod; - this.savingsFrequencyType = account.savingsFrequencyType; - this.totalDepositAmount = account.totalDepositAmount; - this.recurringInterestRate = account.recurringInterestRate; - this.savingInterestRate = account.savingInterestRate; - this.interestType = account.interestType; - this.interestCalculationMethod = account.interestCalculationMethod; - this.tenure = account.tenure; - this.tenureType = account.tenureType; - this.projectedCommencementDate = account.projectedCommencementDate; - this.actualCommencementDate = account.actualCommencementDate; - this.maturesOnDate = account.maturesOnDate; - this.projectedInterestAccuredOnMaturity = account.projectedInterestAccuredOnMaturity; - this.actualInterestAccured = account.actualInterestAccured; - this.projectedMaturityAmount = account.projectedMaturityAmount; - this.actualMaturityAmount = account.actualMaturityAmount; - this.preClosureAllowed = account.preClosureAllowed; - this.preClosureInterestRate = account.preClosureInterestRate; - this.withdrawnonDate = account.withdrawnonDate; - this.rejectedonDate = account.rejectedonDate; - this.closedonDate = account.closedonDate; - this.isLockinPeriodAllowed = account.isLockinPeriodAllowed; - this.lockinPeriod = account.lockinPeriod; - this.lockinPeriodType = account.lockinPeriodType; - this.depositEvery = account.depositEvery; - - this.productOptions = account.productOptions; - this.currencyOptions = account.currencyOptions; - this.savingsProductTypeOptions = account.savingsProductTypeOptions; - this.tenureTypeOptions = account.tenureTypeOptions; - this.savingFrequencyOptions = account.savingFrequencyOptions; - this.savingsInterestTypeOptions = account.savingsInterestTypeOptions; - this.lockinPeriodTypeOptions = account.lockinPeriodTypeOptions; - this.interestCalculationOptions = account.interestCalculationOptions; - this.savingScheduleDatas = account.savingScheduleDatas; - this.permissions = permissions; - this.outstandingAmount = account.outstandingAmount; - this.dueAmount = account.dueAmount; - this.savingScheduleData = account.savingScheduleData; - this.transactions = account.transactions; - this.interestPostEvery = account.interestPostEvery; - this.interestPostFrequency = account.interestPostFrequency; - } - - public SavingAccountData(final SavingAccountData account, final SavingScheduleData savingScheduleData) { - this.id = account.id; - this.status = account.status; - this.externalId = account.externalId; - this.clientId = account.clientId; - this.clientName = account.clientName; - this.productId = account.productId; - this.productName = account.productName; - this.productType = account.productType; - this.currencyData = account.currencyData; - this.savingsDepositAmountPerPeriod = account.savingsDepositAmountPerPeriod; - this.savingsFrequencyType = account.savingsFrequencyType; - this.totalDepositAmount = account.totalDepositAmount; - this.recurringInterestRate = account.recurringInterestRate; - this.savingInterestRate = account.savingInterestRate; - this.interestType = account.interestType; - this.interestCalculationMethod = account.interestCalculationMethod; - this.tenure = account.tenure; - this.tenureType = account.tenureType; - this.projectedCommencementDate = account.projectedCommencementDate; - this.actualCommencementDate = account.actualCommencementDate; - this.maturesOnDate = account.maturesOnDate; - this.projectedInterestAccuredOnMaturity = account.projectedInterestAccuredOnMaturity; - this.actualInterestAccured = account.actualInterestAccured; - this.projectedMaturityAmount = account.projectedMaturityAmount; - this.actualMaturityAmount = account.actualMaturityAmount; - this.preClosureAllowed = account.preClosureAllowed; - this.preClosureInterestRate = account.preClosureInterestRate; - this.withdrawnonDate = account.withdrawnonDate; - this.rejectedonDate = account.rejectedonDate; - this.closedonDate = account.closedonDate; - this.isLockinPeriodAllowed = account.isLockinPeriodAllowed; - this.lockinPeriod = account.lockinPeriod; - this.lockinPeriodType = account.lockinPeriodType; - this.depositEvery = account.depositEvery; - - this.productOptions = account.productOptions; - this.currencyOptions = account.currencyOptions; - this.savingsProductTypeOptions = account.savingsProductTypeOptions; - this.tenureTypeOptions = account.tenureTypeOptions; - this.savingFrequencyOptions = account.savingFrequencyOptions; - this.savingsInterestTypeOptions = account.savingsInterestTypeOptions; - this.lockinPeriodTypeOptions = account.lockinPeriodTypeOptions; - this.interestCalculationOptions = account.interestCalculationOptions; - this.savingScheduleDatas = account.savingScheduleDatas; - this.permissions = account.permissions; - this.outstandingAmount = account.outstandingAmount; - this.dueAmount = account.dueAmount; - this.savingScheduleData = savingScheduleData; - this.transactions = account.transactions; - this.interestPostEvery = account.interestPostEvery; - this.interestPostFrequency = account.interestPostFrequency; - } - - public SavingAccountData(final SavingAccountData account, final Collection transactions) { - this.id = account.id; - this.status = account.status; - this.externalId = account.externalId; - this.clientId = account.clientId; - this.clientName = account.clientName; - this.productId = account.productId; - this.productName = account.productName; - this.productType = account.productType; - this.currencyData = account.currencyData; - this.savingsDepositAmountPerPeriod = account.savingsDepositAmountPerPeriod; - this.savingsFrequencyType = account.savingsFrequencyType; - this.totalDepositAmount = account.totalDepositAmount; - this.recurringInterestRate = account.recurringInterestRate; - this.savingInterestRate = account.savingInterestRate; - this.interestType = account.interestType; - this.interestCalculationMethod = account.interestCalculationMethod; - this.tenure = account.tenure; - this.tenureType = account.tenureType; - this.projectedCommencementDate = account.projectedCommencementDate; - this.actualCommencementDate = account.actualCommencementDate; - this.maturesOnDate = account.maturesOnDate; - this.projectedInterestAccuredOnMaturity = account.projectedInterestAccuredOnMaturity; - this.actualInterestAccured = account.actualInterestAccured; - this.projectedMaturityAmount = account.projectedMaturityAmount; - this.actualMaturityAmount = account.actualMaturityAmount; - this.preClosureAllowed = account.preClosureAllowed; - this.preClosureInterestRate = account.preClosureInterestRate; - this.withdrawnonDate = account.withdrawnonDate; - this.rejectedonDate = account.rejectedonDate; - this.closedonDate = account.closedonDate; - this.isLockinPeriodAllowed = account.isLockinPeriodAllowed; - this.lockinPeriod = account.lockinPeriod; - this.lockinPeriodType = account.lockinPeriodType; - this.depositEvery = account.depositEvery; - - this.productOptions = account.productOptions; - this.currencyOptions = account.currencyOptions; - this.savingsProductTypeOptions = account.savingsProductTypeOptions; - this.tenureTypeOptions = account.tenureTypeOptions; - this.savingFrequencyOptions = account.savingFrequencyOptions; - this.savingsInterestTypeOptions = account.savingsInterestTypeOptions; - this.lockinPeriodTypeOptions = account.lockinPeriodTypeOptions; - this.interestCalculationOptions = account.interestCalculationOptions; - this.savingScheduleDatas = account.savingScheduleDatas; - this.permissions = account.permissions; - this.outstandingAmount = account.outstandingAmount; - this.dueAmount = account.dueAmount; - this.savingScheduleData = account.savingScheduleData; - this.transactions = transactions; - this.interestPostEvery = account.interestPostEvery; - this.interestPostFrequency = account.interestPostFrequency; - } - - public EnumOptionData getStatus() { - return this.status; - } - - public CurrencyData getCurrencyData() { - return this.currencyData; - } - - public BigDecimal getSavingsDepostiAmountPerPeriod() { - return this.savingsDepositAmountPerPeriod; - } - - public Integer getTenure() { - return this.tenure; - } - - public EnumOptionData getTenureType() { - return this.tenureType; - } - - public LocalDate getActualCommencementDate() { - return this.actualCommencementDate; - } - - public LocalDate getMaturesOnDate() { - return this.maturesOnDate; - } - - public Integer getDepositEvery() { - return this.depositEvery; - } - - public BigDecimal getOutstandingAmount() { - return this.outstandingAmount; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountForLookup.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountForLookup.java deleted file mode 100644 index 11fc67541..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountForLookup.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.data; - -public class SavingAccountForLookup { - - private final Long id; - - public SavingAccountForLookup(final Long id) { - this.id = id; - } - - public Long getId() { - return this.id; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountTransactionsData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountTransactionsData.java deleted file mode 100644 index d126f346b..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingAccountTransactionsData.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.data; - -import java.math.BigDecimal; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; - -public class SavingAccountTransactionsData { - - @SuppressWarnings("unused") - private final Long id; - @SuppressWarnings("unused") - private final LocalDate transactionDate; - @SuppressWarnings("unused") - private final EnumOptionData transactionType; - @SuppressWarnings("unused") - private final BigDecimal amount; - - public SavingAccountTransactionsData() { - this.id = null; - this.transactionDate = null; - this.transactionType = null; - this.amount = BigDecimal.ZERO; - } - - public SavingAccountTransactionsData(final Long id, final LocalDate transactionDate, EnumOptionData transactionType, BigDecimal amount){ - this.id = id; - this.transactionDate = transactionDate; - this.transactionType = transactionType; - this.amount = amount; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingPermissionData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingPermissionData.java deleted file mode 100644 index 70fdb1ec7..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingPermissionData.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.data; - -public class SavingPermissionData { - - - - private final boolean rejectAllowed; - private final boolean withdrawnByApplicantAllowed; - private final boolean undoApprovalAllowed; - private final boolean pendingApproval; - private final boolean renewelAllowed; - private final boolean isMaturedDepositAccount; - - private final boolean anyActionOnAccountAllowed; - - public SavingPermissionData(final boolean rejectAllowed, final boolean withdrawnByApplicantAllowed, final boolean undoApprovalAllowed, - final boolean pendingApproval, final boolean renewelAllowed, final boolean isMaturedDepositAccount) { - this.rejectAllowed = rejectAllowed; - this.withdrawnByApplicantAllowed = withdrawnByApplicantAllowed; - this.undoApprovalAllowed = undoApprovalAllowed; - this.pendingApproval = pendingApproval; - this.renewelAllowed = renewelAllowed; - this.isMaturedDepositAccount = isMaturedDepositAccount; - this.anyActionOnAccountAllowed = isRejectAllowed() || isPendingApproval() || isUndoApprovalAllowed() - || isWithdrawnByApplicantAllowed() || isRenewelAllowed() || isMaturedDepositAccount(); - } - - public boolean isRejectAllowed() { - return rejectAllowed; - } - - public boolean isWithdrawnByApplicantAllowed() { - return withdrawnByApplicantAllowed; - } - - public boolean isUndoApprovalAllowed() { - return undoApprovalAllowed; - } - - public boolean isPendingApproval() { - return pendingApproval; - } - - public boolean isAnyActionOnAccountAllowed() { - return anyActionOnAccountAllowed; - } - - public boolean isRenewelAllowed() { - return renewelAllowed; - } - - public boolean isMaturedDepositAccount() { - return isMaturedDepositAccount; - } - - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingScheduleData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingScheduleData.java deleted file mode 100644 index 722c33294..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingScheduleData.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.data; - -import java.math.BigDecimal; -import java.util.Collection; - -import org.mifosplatform.organisation.monetary.data.CurrencyData; - -public class SavingScheduleData { - - private final CurrencyData currency; - private final BigDecimal cumulativeDepositDue; - private final BigDecimal cumulativeDepositPaid; - private final BigDecimal cummulativeInterestAccured; - private final Collection periods; - - public SavingScheduleData(final CurrencyData currency, final BigDecimal cumulativeDepositDue, final BigDecimal cumulativeDepositPaid, - final BigDecimal cummulativeInterestAccured, final Collection periods) { - this.currency = currency; - this.cumulativeDepositDue = cumulativeDepositDue; - this.cumulativeDepositPaid = cumulativeDepositPaid; - this.cummulativeInterestAccured = cummulativeInterestAccured; - this.periods = periods; - - } - - public CurrencyData getCurrency() { - return this.currency; - } - - public BigDecimal getCumulativeDepositDue() { - return this.cumulativeDepositDue; - } - - public BigDecimal getCumulativeDepositPaid() { - return this.cumulativeDepositPaid; - } - - public BigDecimal getCummulativeInterestAccured() { - return this.cummulativeInterestAccured; - } - - public Collection getPeriods() { - return this.periods; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingSchedulePeriodData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingSchedulePeriodData.java deleted file mode 100644 index 6e9f687a2..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/data/SavingSchedulePeriodData.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.data; - -import java.math.BigDecimal; - -import org.joda.time.LocalDate; - -public class SavingSchedulePeriodData { - - private final Integer period; - private final LocalDate dueDate; - private final BigDecimal depositDue; - private final BigDecimal depositPaid; - private final BigDecimal interestAccured; - - public SavingSchedulePeriodData(final Integer period, final LocalDate dueDate, final BigDecimal depositDue, final BigDecimal depositPaid, final BigDecimal interestAccured) { - this.period = period; - this.dueDate = dueDate; - this.depositDue = depositDue; - this.depositPaid = depositPaid; - this.interestAccured = interestAccured; - } - - public static SavingSchedulePeriodData addScheduleInformation(int periodNumber, LocalDate scheduleDate, - BigDecimal depositAmountPerPeriod, BigDecimal interestAccured) { - return new SavingSchedulePeriodData(periodNumber, scheduleDate, depositAmountPerPeriod, BigDecimal.ZERO, interestAccured); - } - - public Integer getPeriod() { - return this.period; - } - - public LocalDate getDueDate() { - return this.dueDate; - } - - public BigDecimal getDepositDue() { - return this.depositDue; - } - - public BigDecimal getDepositPaid() { - return this.depositPaid; - } - - public BigDecimal getInterestAccured() { - return this.interestAccured; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/DepositScheduleDateGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/DepositScheduleDateGenerator.java deleted file mode 100644 index 35904e1eb..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/DepositScheduleDateGenerator.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.domain; - -import java.util.List; - -import org.joda.time.LocalDate; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; - -public interface DepositScheduleDateGenerator { - - List generate(LocalDate startDate, Integer paymentPeriods, Integer depositFrequency, SavingFrequencyType savingFrequencyType); -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/ReccuringDepositInterestCalculator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/ReccuringDepositInterestCalculator.java deleted file mode 100644 index 5a3553ee5..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/ReccuringDepositInterestCalculator.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.domain; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.springframework.stereotype.Service; - -@Service -public class ReccuringDepositInterestCalculator { - - private final Integer monthsInYear = 12; - - public Money calculateInterestOnMaturityFor(final Money savingsDepositPerPeriod, final Integer tenure, - final BigDecimal reccuringInterestRate, final SavingFrequencyType savingFrequencyType, - final SavingInterestCalculationMethod savingInterestCalculationMethod, Integer depositEvery) { - - BigDecimal finalAmount = BigDecimal.ZERO; - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - - BigDecimal interestRateAsFraction = reccuringInterestRate.divide(BigDecimal.valueOf(100), mc); - Integer noofTimesInterestCompoundPerYear = determineIntValue(savingFrequencyType); - - BigDecimal interestRatePerPeriod = BigDecimal.valueOf(interestRateAsFraction.doubleValue() - / noofTimesInterestCompoundPerYear.doubleValue()); - Integer noOfTimestobeCalculated = tenure / depositEvery; - - if (savingInterestCalculationMethod.isAverageBalance()) { - - BigDecimal termAmount = BigDecimal.ZERO; - BigDecimal totalInterest = BigDecimal.ZERO; - BigDecimal closingBalance = BigDecimal.ZERO; - BigDecimal amountPerPeriod = savingsDepositPerPeriod.getAmount(); - Integer depositEveryOriginalValue = depositEvery; - BigDecimal amountPermonth = BigDecimal.valueOf(amountPerPeriod.doubleValue() / depositEvery.doubleValue()); - - while (noOfTimestobeCalculated > 0) { - while (depositEvery > 0) { - closingBalance = closingBalance.add(amountPermonth); - termAmount = termAmount.add(closingBalance); - depositEvery--; - } - - BigDecimal averageAmount = BigDecimal.valueOf(termAmount.doubleValue() / depositEveryOriginalValue.doubleValue()); - BigDecimal interestRatePerTerm = BigDecimal.valueOf(interestRateAsFraction.doubleValue() / monthsInYear.doubleValue() - * depositEveryOriginalValue.doubleValue()); - BigDecimal interestperTerm = averageAmount.multiply(interestRatePerTerm); - totalInterest = totalInterest.add(interestperTerm); - depositEvery = depositEveryOriginalValue; - termAmount = BigDecimal.ZERO; - noOfTimestobeCalculated--; - } - finalAmount = closingBalance.add(totalInterest); - - } else if (savingInterestCalculationMethod.isMonthlyCollection()) { - /* - * // Assuming tenure in months // see - * http://www.onemint.com/2012/04/03/ - * how-to-calculate-interest-on-recurring-deposits/ - * - * A=P(1+r/n)^nt - * - * A = final amount P = principal amount (initial investment) r = - * annual nominal interest rate (as a decimal, not in percentage) n - * = number of times the interest is compounded per year t = number - * of years - */ - - BigDecimal onePlusInterestRatePerPeriod = BigDecimal.ONE.add(interestRatePerPeriod); - BigDecimal monthsExpressedInYears; - BigDecimal timeforOneCalculationPeriod; - BigDecimal amountPerPeriod; - Integer tempTenure = tenure; - while (noOfTimestobeCalculated > 0) { - monthsExpressedInYears = BigDecimal.valueOf(tempTenure.doubleValue() / monthsInYear.doubleValue()); - timeforOneCalculationPeriod = BigDecimal.valueOf(noofTimesInterestCompoundPerYear * monthsExpressedInYears.doubleValue()); - amountPerPeriod = savingsDepositPerPeriod.getAmount() - .multiply( - BigDecimal.valueOf(Math.pow(onePlusInterestRatePerPeriod.doubleValue(), - timeforOneCalculationPeriod.doubleValue()))); - finalAmount = finalAmount.add(amountPerPeriod); - noOfTimestobeCalculated--; - tempTenure = tempTenure - depositEvery; - } - } - return Money.of(savingsDepositPerPeriod.getCurrency(), finalAmount); - } - - private Integer determineIntValue(final SavingFrequencyType frequencyType) { - Integer noofTimesInterestCompoundPerYear = Integer.valueOf(0); - switch (frequencyType) { - case MONTHLY: - noofTimesInterestCompoundPerYear = monthsInYear; - break; - case QUATERLY: - noofTimesInterestCompoundPerYear = monthsInYear / 3; - break; - case HALFYEARLY: - noofTimesInterestCompoundPerYear = monthsInYear / 6; - break; - case YEARLY: - noofTimesInterestCompoundPerYear = monthsInYear / 12; - break; - default: - throw new RuntimeException("The specified frequency not supported"); - - } - return noofTimesInterestCompoundPerYear; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccount.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccount.java deleted file mode 100644 index 7eca5393b..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccount.java +++ /dev/null @@ -1,730 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.domain; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.UniqueConstraint; - -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; -import org.joda.time.LocalDate; -import org.joda.time.Months; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.client.domain.Client; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountEvent; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountStatus; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachine; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.InvalidDepositStateTransitionException; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.mifosplatform.useradministration.domain.AppUser; - -@Entity -@Table(name = "m_saving_account", uniqueConstraints = @UniqueConstraint(name = "saving_acc_external_id", columnNames = { "external_id" })) -public class SavingAccount extends AbstractAuditableCustom { - - @ManyToOne - @JoinColumn(name = "client_id", nullable = false) - private Client client; - - @ManyToOne - @JoinColumn(name = "product_id") - private SavingProduct product; - - @Column(name = "savings_product_type", nullable = false) - private Integer savingProductType; - - @Column(name = "external_id") - private String externalId; - - @Embedded - private MonetaryCurrency currency; - - @Column(name = "deposit_amount_per_period", scale = 6, precision = 19, nullable = false) - private BigDecimal savingsDepositAmountPerPeriod; - - @Column(name = "total_deposit_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal totalSavingsAmount; - - @Column(name = "reccuring_nominal_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal reccuringInterestRate; - - @Column(name = "regular_saving_nominal_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal savingInterestRate; - - @Column(name = "tenure", nullable = false) - private Integer tenure; - - @Column(name = "tenure_type", nullable = false) - private Integer tenureType; - - @Column(name = "frequency", nullable = false) - private Integer frequency; - - @Column(name = "interest_type", nullable = false) - private Integer interestType; - - @Column(name = "interest_calculation_method") - private Integer interestCalculationMethod; - - @Temporal(TemporalType.DATE) - @Column(name = "projected_commencement_date") - private Date projectedCommencementDate; - - @Temporal(TemporalType.DATE) - @Column(name = "actual_commencement_date") - private Date actualCommencementDate; - - @SuppressWarnings("unused") - @Temporal(TemporalType.DATE) - @Column(name = "matures_on_date") - private Date maturesOnDate; - - @SuppressWarnings("unused") - @Column(name = "projected_interest_accrued_on_maturity", scale = 6, precision = 19, nullable = false) - private BigDecimal projectedInterestAccruedOnMaturity; - - @SuppressWarnings("unused") - @Column(name = "actual_interest_accrued", scale = 6, precision = 19, nullable = false) - private BigDecimal interestAccrued; - - @SuppressWarnings("unused") - @Column(name = "projected_total_maturity_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal projectedTotalOnMaturity; - - @SuppressWarnings("unused") - @Column(name = "actual_total_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal total; - - @Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal preClosureInterestRate; - - @Column(name = "outstanding_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal outstandingAmount; - - @Column(name = "is_preclosure_allowed", nullable = false) - private final boolean preClosureAllowed = false; - - @Column(name = "is_deleted", nullable = false) - private boolean deleted = false; - - @Column(name = "status_enum", nullable = false) - private Integer accountStatus; - - @SuppressWarnings("unused") - @Temporal(TemporalType.DATE) - @Column(name = "closedon_date") - private Date closedOnDate; - - @SuppressWarnings("unused") - @Temporal(TemporalType.DATE) - @Column(name = "rejectedon_date") - private Date rejectedOnDate; - - @Temporal(TemporalType.DATE) - @Column(name = "withdrawnon_date") - private Date withdrawnOnDate; - - @Column(name = "is_lock_in_period_allowed", nullable = false) - private boolean isLockinPeriodAllowed = false; - - @Column(name = "lock_in_period", nullable = false) - private Integer lockinPeriod; - - @Column(name = "lock_in_period_type", nullable = false) - private Integer lockinPeriodType; - - @Column(name = "deposit_every", nullable = false) - private Integer payEvery; - - @Column(name = "interest_posting_every", nullable = false) - private Integer interestPostEvery; - - @Column(name = "interest_posting_frequency", nullable = false) - private Integer interestPostFrequency; - - @Column(name = "interest_posted_amount", scale = 6, precision = 19) - private BigDecimal interestPostedAmount; - - @Temporal(TemporalType.DATE) - @Column(name = "last_interest_posted_date") - private Date lastInterestPostedDate; - - @Temporal(TemporalType.DATE) - @Column(name = "next_interest_posting_date") - private Date nextInterestPostingDate; - - // see - // http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags - @LazyCollection(LazyCollectionOption.FALSE) - @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingAccount", orphanRemoval = true) - private final List savingScheduleInstallments = new ArrayList(); - - @OrderBy(value = "id") - @LazyCollection(LazyCollectionOption.FALSE) - @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingAccount", orphanRemoval = true) - private final List savingAccountTransactions = new ArrayList(); - - protected SavingAccount() { - // - } - - public static SavingAccount openNew(final Client client, final SavingProduct product, final String externalId, - final Money savingsDeposit, final BigDecimal reccuringInterestRate, final BigDecimal savingInterestRate, final Integer tenure, - final LocalDate commencementDate, final TenureTypeEnum tenureTypeEnum, final SavingProductType savingProductType, - final SavingFrequencyType savingFrequencyType, final SavingsInterestType interestType, - final SavingInterestCalculationMethod savingInterestCalculationMethod, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType, - final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator, - final DepositLifecycleStateMachine lifecycleStateMachine, final Integer depositEvery, final Integer interestPostEvery, - final Integer interestPostFrequency) { - - Money futureValueOnMaturity = null; - if (savingProductType.isReccuring() && tenureTypeEnum.isFixedPeriod()) { - futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, - reccuringInterestRate, savingFrequencyType, savingInterestCalculationMethod, depositEvery); - } else if (savingProductType.isReccuring() && tenureTypeEnum.isPerpetual()) { - futureValueOnMaturity = savingsDeposit; - } else { - futureValueOnMaturity = savingsDeposit; - } - - return new SavingAccount(client, externalId, product, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure, - commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, interestType, savingInterestCalculationMethod, - isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, futureValueOnMaturity, lifecycleStateMachine, depositEvery, - interestPostEvery, interestPostFrequency); - } - - public SavingAccount(final Client client, final String externalId, final SavingProduct product, final Money savingsDeposit, - final BigDecimal reccuringInterestRate, final BigDecimal savingInterestRate, final Integer tenure, - final LocalDate commencementDate, final TenureTypeEnum tenureTypeEnum, final SavingProductType savingProductType, - final SavingFrequencyType savingFrequencyType, final SavingsInterestType interestType, - final SavingInterestCalculationMethod savingInterestCalculationMethod, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType, final Money futureValueOnMaturity, - final DepositLifecycleStateMachine lifecycleStateMachine, final Integer payEvery, final Integer interestPostEvery, - final Integer interestPostFrequency) { - - DepositAccountStatus from = null; - if (accountStatus != null) { - from = DepositAccountStatus.fromInt(accountStatus); - } - - DepositAccountStatus statusEnum = lifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CREATED, from); - accountStatus = statusEnum.getValue(); - - this.total = BigDecimal.ZERO; - this.preClosureInterestRate = BigDecimal.ZERO; - this.totalSavingsAmount = BigDecimal.ZERO; - this.interestAccrued = BigDecimal.ZERO; - - this.client = client; - this.externalId = externalId; - this.product = product; - this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount(); - this.currency = savingsDeposit.getCurrency(); - this.reccuringInterestRate = reccuringInterestRate; - this.savingInterestRate = savingInterestRate; - this.tenure = tenure; - this.projectedCommencementDate = commencementDate.toDate(); - this.tenureType = tenureTypeEnum.getValue(); - this.savingProductType = savingProductType.getValue(); - this.frequency = savingFrequencyType.getValue(); - this.interestType = interestType.getValue(); - this.interestCalculationMethod = savingInterestCalculationMethod.getValue(); - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType.getValue(); - this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount(); - BigDecimal projectedInterestForReccuring = futureValueOnMaturity.getAmount().subtract( - BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue() * tenure.doubleValue() / payEvery)); // presently - // only - // for - // months - this.projectedInterestAccruedOnMaturity = savingProductType.isReccuring() && tenureTypeEnum.isFixedPeriod() ? projectedInterestForReccuring - : BigDecimal.ZERO; - this.payEvery = payEvery; - this.outstandingAmount = BigDecimal.ZERO; - this.interestPostEvery = interestPostEvery; - this.interestPostFrequency = interestPostFrequency; - } - - public void modifyAccount(final SavingProduct product, final String externalId, final Money savingsDeposit, - final BigDecimal reccuringInterestRate, final BigDecimal savingInterestRate, final Integer tenure, - final LocalDate commencementDate, final TenureTypeEnum tenureTypeEnum, final SavingProductType savingProductType, - final SavingFrequencyType savingFrequencyType, final SavingInterestCalculationMethod savingInterestCalculationMethod, - final boolean isLockinPeriodAllowed, final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType, - final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator, final Integer payEvery, - final SavingsInterestType interestType, final Integer interestPostEvery, final Integer interestPostFrequency) { - - Money futureValueOnMaturity = null; - if (savingProductType.isReccuring() && tenureTypeEnum.isFixedPeriod()) { - futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsDeposit, tenure, - reccuringInterestRate, savingFrequencyType, savingInterestCalculationMethod, payEvery); - } else if (savingProductType.isReccuring() && tenureTypeEnum.isPerpetual()) { - futureValueOnMaturity = savingsDeposit; - } else { - futureValueOnMaturity = savingsDeposit; - } - - this.product = product; - this.externalId = externalId; - this.savingsDepositAmountPerPeriod = savingsDeposit.getAmount(); - this.reccuringInterestRate = reccuringInterestRate; - this.savingInterestRate = savingInterestRate; - this.tenure = tenure; - this.projectedCommencementDate = commencementDate.toDate(); - this.tenureType = tenureTypeEnum.getValue(); - this.savingProductType = savingProductType.getValue(); - this.frequency = savingFrequencyType.getValue(); - this.interestType = interestType.getValue(); - this.interestCalculationMethod = savingInterestCalculationMethod.getValue(); - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType.getValue(); - this.payEvery = payEvery; - this.outstandingAmount = BigDecimal.ZERO; - this.interestPostEvery = interestPostEvery; - this.interestPostFrequency = interestPostFrequency; - this.savingScheduleInstallments.clear(); - - this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount(); - BigDecimal projectedInterestForReccuring = futureValueOnMaturity.getAmount().subtract( - BigDecimal.valueOf(savingsDeposit.getAmount().doubleValue() * tenure.doubleValue() / payEvery)); // presently - // only - // for - // months - this.projectedInterestAccruedOnMaturity = savingProductType.isReccuring() && tenureTypeEnum.isFixedPeriod() ? projectedInterestForReccuring - : BigDecimal.ZERO; - } - - public boolean isDeleted() { - return this.deleted; - } - - public boolean isPendingApproval() { - return this.accountStatus.equals(100); - } - - public Client getClient() { - return client; - } - - public SavingProduct getProduct() { - return product; - } - - public Integer getSavingProductType() { - return savingProductType; - } - - public String getExternalId() { - return externalId; - } - - public BigDecimal getSavingsDepositAmountPerPeriod() { - return savingsDepositAmountPerPeriod; - } - - public BigDecimal getReccuringInterestRate() { - return reccuringInterestRate; - } - - public BigDecimal getSavingInterestRate() { - return savingInterestRate; - } - - public Integer getTenure() { - return tenure; - } - - public Integer getTenureType() { - return tenureType; - } - - public Integer getFrequency() { - return frequency; - } - - public Integer getInterestType() { - return interestType; - } - - public Integer getInterestCalculationMethod() { - return interestCalculationMethod; - } - - public Date getProjectedCommencementDate() { - return projectedCommencementDate; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public boolean isPreClosureAllowed() { - return preClosureAllowed; - } - - public Date getWithdrawnOnDate() { - return withdrawnOnDate; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public Integer getLockinPeriodType() { - return lockinPeriodType; - } - - public Integer getPayEvery() { - return this.payEvery; - } - - public BigDecimal getOutstandingAmount() { - return this.outstandingAmount; - } - - public Integer getInterestPostEvery() { - return this.interestPostEvery; - } - - public Integer getInterestPostFrequency() { - return this.interestPostFrequency; - } - - public List getSavingAccountTransactions() { - return this.savingAccountTransactions; - } - - public void addSavingScheduleInstallment(final SavingScheduleInstallments installment) { - installment.updateAccount(this); - this.savingScheduleInstallments.add(installment); - } - - public void reject(final LocalDate rejectedOn, final DepositLifecycleStateMachine depositLifecycleStateMachine) { - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_REJECTED, - DepositAccountStatus.fromInt(this.accountStatus)); - this.accountStatus = statusEnum.getValue(); - - this.maturesOnDate = null; - this.rejectedOnDate = rejectedOn.toDateTimeAtCurrentTime().toDate(); - this.closedOnDate = rejectedOn.toDateTimeAtCurrentTime().toDate(); - - if (rejectedOn.isBefore(projectedCommencementDate())) { - - final String errorMessage = "The date on which a saving account is rejected cannot be before its submittal date: " - + projectedCommencementDate().toString(); - throw new InvalidDepositStateTransitionException("reject", "cannot.be.before.submittal.date", errorMessage, rejectedOn, - projectedCommencementDate()); - - } - if (rejectedOn.isAfter(new LocalDate())) { - - final String errorMessage = "The date on which a saving account is rejected cannot be in the future."; - throw new InvalidDepositStateTransitionException("reject", "cannot.be.a.future.date", errorMessage, rejectedOn); - - } - - } - - public LocalDate projectedCommencementDate() { - LocalDate date = null; - if (this.projectedCommencementDate != null) { - date = new LocalDate(this.projectedCommencementDate); - } - return date; - } - - public void withdrawnByApplicant(final LocalDate withdrawnOn, final DepositLifecycleStateMachine depositLifecycleStateMachine) { - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_WITHDRAWN, - DepositAccountStatus.fromInt(this.accountStatus)); - this.accountStatus = statusEnum.getValue(); - - this.maturesOnDate = null; - this.withdrawnOnDate = withdrawnOn.toDateTimeAtCurrentTime().toDate(); - this.closedOnDate = withdrawnOn.toDateTimeAtCurrentTime().toDate(); - this.savingScheduleInstallments.clear(); - - if (withdrawnOn.isBefore(projectedCommencementDate())) { - - final String errorMessage = "The date on which a deposit is rejected cannot be before its submittal date: " - + projectedCommencementDate().toString(); - throw new InvalidDepositStateTransitionException("withdrawnbyclient", "cannot.be.before.submittal.date", errorMessage, - withdrawnOn, projectedCommencementDate()); - - } - - if (withdrawnOn.isAfter(new LocalDate())) { - final String errorMessage = "The date on which a deposit is rejected cannot be in the future."; - throw new InvalidDepositStateTransitionException("withdrawnbyclient", "cannot.be.a.future.date", errorMessage, withdrawnOn); - } - } - - public void undoSavingAccountApproval(final DepositLifecycleStateMachine depositLifecycleStateMachine) { - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_APPROVAL_UNDO, - DepositAccountStatus.fromInt(this.accountStatus)); - this.accountStatus = statusEnum.getValue(); - this.savingScheduleInstallments.clear(); - this.closedOnDate = new Date(); - } - - public void approveSavingAccount(final LocalDate approvalDate, final BigDecimal savingsDepositAmountPerPeriod, - final BigDecimal recurringInterestRate, final BigDecimal savingInterestRate, final Integer interestType, final Integer tenure, - final Integer tenureType, final Integer frequency, final Integer payEvery, - final DepositLifecycleStateMachine depositLifecycleStateMachine, - final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator, final Integer interestPostEvery, - final Integer interestPostFrequency) { - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_APPROVED, - DepositAccountStatus.fromInt(this.accountStatus)); - this.accountStatus = statusEnum.getValue(); - - Money savingsAmountPerPeriod = Money.of(currency, savingsDepositAmountPerPeriod); - TenureTypeEnum tenureTypeEnum = TenureTypeEnum.fromInt(tenureType); - SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(frequency); - SavingInterestCalculationMethod interestCalculationMethod = SavingInterestCalculationMethod.fromInt(this.interestCalculationMethod); - - Money futureValueOnMaturity = null; - if (SavingProductType.fromInt(this.savingProductType).isReccuring() && tenureTypeEnum.isFixedPeriod()) { - futureValueOnMaturity = reccuringDepositInterestCalculator.calculateInterestOnMaturityFor(savingsAmountPerPeriod, tenure, - recurringInterestRate, savingFrequencyType, interestCalculationMethod, payEvery); - } else if (SavingProductType.fromInt(this.savingProductType).isReccuring() && tenureTypeEnum.isPerpetual()) { - futureValueOnMaturity = savingsAmountPerPeriod; - } else { - futureValueOnMaturity = savingsAmountPerPeriod; - } - - this.actualCommencementDate = approvalDate.toDate(); - this.savingsDepositAmountPerPeriod = savingsDepositAmountPerPeriod; - this.reccuringInterestRate = recurringInterestRate; - this.savingInterestRate = savingInterestRate; - this.interestType = interestType; - this.tenure = tenure; - this.tenureType = tenureType; - this.frequency = frequency; - this.payEvery = payEvery; - this.savingScheduleInstallments.clear(); - this.total = futureValueOnMaturity.getAmount(); - BigDecimal interestForReccuring = futureValueOnMaturity.getAmount().subtract( - BigDecimal.valueOf(savingsDepositAmountPerPeriod.doubleValue() * tenure.doubleValue() / payEvery.doubleValue())); // presently - // only - // for - // months - this.interestAccrued = SavingProductType.fromInt(this.savingProductType).isReccuring() && tenureTypeEnum.isFixedPeriod() ? interestForReccuring - : BigDecimal.ZERO; - this.interestPostEvery = interestPostEvery; - this.interestPostFrequency = interestPostFrequency; - - // for interest posting initializing - this.lastInterestPostedDate = this.actualCommencementDate; - this.nextInterestPostingDate = new LocalDate(this.lastInterestPostedDate).plusMonths(this.interestPostEvery).toDate(); - this.interestPostedAmount = BigDecimal.ZERO; - } - - public void depositMoney(final JsonCommand command) { - - final BigDecimal depositAmountCommandValue = command.bigDecimalValueOfParameterNamed("savingsDepositAmountPerPeriod"); - final LocalDate depositDateCommandValue = command.localDateValueOfParameterNamed("depositDate"); - - BigDecimal depositAmount = BigDecimal.ZERO; - BigDecimal remainAmountToBePaid = BigDecimal.ZERO; - BigDecimal commandRemainDepositAmount = depositAmountCommandValue; - - SavingAccountTransaction savingAccountTransaction = SavingAccountTransaction.deposit(depositAmountCommandValue, - depositDateCommandValue); - savingAccountTransaction.updateAccount(this); - this.savingAccountTransactions.add(savingAccountTransaction); - this.outstandingAmount = this.outstandingAmount.add(depositAmountCommandValue); - this.totalSavingsAmount = this.totalSavingsAmount.add(depositAmountCommandValue); - - if (SavingProductType.fromInt(this.savingProductType).isReccuring() && TenureTypeEnum.fromInt(tenureType).isFixedPeriod()) { - for (SavingScheduleInstallments savingScheduleInstallment : this.savingScheduleInstallments) { - if (!savingScheduleInstallment.isCompleted()) { - depositAmount = savingScheduleInstallment.getDeposit(); - remainAmountToBePaid = depositAmount.subtract(savingScheduleInstallment.getDepositPaid()); - if (remainAmountToBePaid.doubleValue() > 0) { - if (commandRemainDepositAmount.doubleValue() > 0) { - if (commandRemainDepositAmount.doubleValue() >= remainAmountToBePaid.doubleValue()) { - savingScheduleInstallment.setDepositPaid(remainAmountToBePaid.add(savingScheduleInstallment - .getDepositPaid())); - savingScheduleInstallment.setPaymentDate(depositDateCommandValue.toDate()); - savingScheduleInstallment.setCompleted(true); - commandRemainDepositAmount = commandRemainDepositAmount.subtract(remainAmountToBePaid); - } else if (commandRemainDepositAmount.doubleValue() < remainAmountToBePaid.doubleValue()) { - savingScheduleInstallment.setDepositPaid(commandRemainDepositAmount.add(savingScheduleInstallment - .getDepositPaid())); - savingScheduleInstallment.setPaymentDate(depositDateCommandValue.toDate()); - commandRemainDepositAmount = BigDecimal.ZERO; - } - } - } - } - } - } else { - for (SavingScheduleInstallments savingScheduleInstallment : this.savingScheduleInstallments) { - savingScheduleInstallment.setDepositPaid(remainAmountToBePaid.add(savingScheduleInstallment.getDepositPaid())); - savingScheduleInstallment.setPaymentDate(depositDateCommandValue.toDate()); - } - } - } - - public boolean isActive() { - return DepositAccountStatus.fromInt(this.accountStatus).isActive(); - } - - public void withdrawAmount(final BigDecimal amount, final LocalDate transactionDate) { - this.outstandingAmount = this.outstandingAmount.subtract(amount); - SavingAccountTransaction savingAccountTransaction = SavingAccountTransaction.withdraw(amount, transactionDate); - savingAccountTransaction.updateAccount(this); - this.savingAccountTransactions.add(savingAccountTransaction); - } - - /** - * Delete is a soft delete. Updates flag on account so it wont appear - * in query/report results. - * - * Any fields with unique constraints and prepended with id of record. - */ - public void delete() { - this.deleted = true; - this.externalId = this.getId() + "_" + this.externalId; - } - - public void postInterest() { - - LocalDate lastInterestPostedDate = getLastInterestPostedDate(); - // LocalDate nextInterestPostingDate = getNextInterestPostedDate(); - // SavingInterestCalculationMethod savingInterestCalculationMethod = - // SavingInterestCalculationMethod - // .fromInt(this.interestCalculationMethod); - - Integer monthsForInterestCalculation = Months.monthsBetween(lastInterestPostedDate, new LocalDate()).getMonths(); - Integer postInterestItereations = monthsForInterestCalculation / this.interestPostEvery; - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - BigDecimal interestRateAsFraction = reccuringInterestRate.divide(BigDecimal.valueOf(100), mc); - final Integer monthsInYear = 12; - - BigDecimal totalDepositedAmount = BigDecimal.ZERO; - BigDecimal totalWithdrawableAmount = BigDecimal.ZERO; - BigDecimal totalOutstandingAmount = BigDecimal.ZERO; - boolean isOutstandingAmountCalculated = false; - - while (postInterestItereations > 0) { - lastInterestPostedDate = getLastInterestPostedDate(); - // nextInterestPostingDate = getNextInterestPostedDate(); - LocalDate transactionStartDate = lastInterestPostedDate; - - BigDecimal termTotalAmount = BigDecimal.ZERO; - BigDecimal averageBalanceForTerm = BigDecimal.ZERO; - - for (int i = 0; i < interestPostEvery; i++) { - // default for months here - LocalDate transactionEndDate = transactionStartDate.plusMonths(1); - BigDecimal depositedAmount = BigDecimal.ZERO; - BigDecimal withdrawableAmount = BigDecimal.ZERO; - BigDecimal outstandingAmount = BigDecimal.ZERO; - - for (SavingAccountTransaction savingAccountTransaction : this.savingAccountTransactions) { - LocalDate actualTransactionDate = savingAccountTransaction.getTransactionDate(); - if (actualTransactionDate != null - && (actualTransactionDate.isAfter(transactionStartDate) || actualTransactionDate.isEqual(transactionStartDate))) { - if (actualTransactionDate.isBefore(transactionEndDate)) { - if (savingAccountTransaction.getTypeOf().isDeposit()) { - depositedAmount = depositedAmount.add(savingAccountTransaction.getAmount()); - } else if (savingAccountTransaction.getTypeOf().isWithdraw()) { - withdrawableAmount = withdrawableAmount.add(savingAccountTransaction.getAmount()); - } - } - } else if (actualTransactionDate != null && (actualTransactionDate.isBefore(transactionStartDate))) { - if (!isOutstandingAmountCalculated) { - if (savingAccountTransaction.getTypeOf().isDeposit()) { - depositedAmount = depositedAmount.add(savingAccountTransaction.getAmount()); - } else if (savingAccountTransaction.getTypeOf().isWithdraw()) { - withdrawableAmount = withdrawableAmount.add(savingAccountTransaction.getAmount()); - } - } - } - } - outstandingAmount = depositedAmount.subtract(withdrawableAmount); - totalDepositedAmount = totalDepositedAmount.add(depositedAmount); - totalWithdrawableAmount = totalWithdrawableAmount.add(withdrawableAmount); - totalOutstandingAmount = totalOutstandingAmount.add(outstandingAmount); - termTotalAmount = termTotalAmount.add(totalOutstandingAmount); - transactionStartDate = transactionEndDate; - isOutstandingAmountCalculated = true; - - } - // TODO - HUGO - calculate interest on calculation method - - // if (savingInterestCalculationMethod.isAverageBalance()) { - averageBalanceForTerm = BigDecimal.valueOf(termTotalAmount.doubleValue() / this.interestPostEvery); - BigDecimal interestRatePerTerm = BigDecimal.valueOf(interestRateAsFraction.doubleValue() / monthsInYear.doubleValue() - * this.interestPostEvery.doubleValue()); - BigDecimal interestPerTerm = averageBalanceForTerm.multiply(interestRatePerTerm); - this.interestPostedAmount = this.interestPostedAmount.add(interestPerTerm); - totalOutstandingAmount = totalOutstandingAmount.add(interestPerTerm); - // } else if(savingInterestCalculationMethod.isMonthlyCollection()){ - - // } - this.outstandingAmount = this.outstandingAmount.add(interestPerTerm); - this.lastInterestPostedDate = getNextInterestPostedDate().toDate(); - this.nextInterestPostingDate = getNextInterestPostedDate().plusMonths(this.interestPostEvery).toDate(); - postInterestItereations--; - } - } - - private final LocalDate getLastInterestPostedDate() { - LocalDate lastInterestPostedDate; - if (this.lastInterestPostedDate == null) { - lastInterestPostedDate = new LocalDate(this.actualCommencementDate); - } else { - lastInterestPostedDate = new LocalDate(this.lastInterestPostedDate); - } - return lastInterestPostedDate; - } - - private final LocalDate getNextInterestPostedDate() { - LocalDate nextInterestPostingDate; - if (this.nextInterestPostingDate == null) { - nextInterestPostingDate = new LocalDate(this.nextInterestPostingDate).plusMonths(this.interestPostEvery); - } else { - nextInterestPostingDate = new LocalDate(this.nextInterestPostingDate); - } - return nextInterestPostingDate; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountTransaction.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountTransaction.java deleted file mode 100644 index 238412099..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingAccountTransaction.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.domain; - -import java.math.BigDecimal; -import java.util.Date; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountTransactionType; -import org.mifosplatform.useradministration.domain.AppUser; - -@Entity -@Table(name = "m_saving_account_transaction") -public class SavingAccountTransaction extends AbstractAuditableCustom { - - @SuppressWarnings("unused") - @ManyToOne(optional = false) - @JoinColumn(name = "saving_account_id", nullable = false) - private SavingAccount savingAccount; - - @Column(name = "transaction_type_enum", nullable = false) - private Integer typeOf; - - @SuppressWarnings("unused") - @OneToOne(optional = true, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "contra_id") - private SavingAccountTransaction contra; - - @Temporal(TemporalType.DATE) - @Column(name = "transaction_date", nullable = false) - private final Date transactionDate; - - @Column(name = "amount", scale = 6, precision = 19, nullable = false) - private final BigDecimal amount; - - public SavingAccountTransaction() { - this.transactionDate = null; - this.amount = BigDecimal.ZERO; - } - - public SavingAccountTransaction(final DepositAccountTransactionType transactionType, final BigDecimal amount, - final LocalDate paymentDate) { - this.typeOf = transactionType.getValue(); - this.amount = amount; - this.transactionDate = paymentDate.toDate(); - } - - public static SavingAccountTransaction deposit(final BigDecimal amount, final LocalDate paymentDate) { - return new SavingAccountTransaction(DepositAccountTransactionType.DEPOSIT, amount == null ? new BigDecimal(0) : amount, paymentDate); - } - - public static SavingAccountTransaction withdraw(final BigDecimal amount, final LocalDate paymentDate) { - return new SavingAccountTransaction(DepositAccountTransactionType.WITHDRAW, amount == null ? new BigDecimal(0) : amount, - paymentDate); - } - - public static SavingAccountTransaction postInterest(final BigDecimal amount, final LocalDate paymentDate) { - return new SavingAccountTransaction(DepositAccountTransactionType.INTEREST_POSTING, amount == null ? new BigDecimal(0) : amount, - paymentDate); - } - - public void updateAccount(final SavingAccount savingAccount) { - this.savingAccount = savingAccount; - } - - public DepositAccountTransactionType getTypeOf() { - return DepositAccountTransactionType.fromInt(this.typeOf); - } - - public BigDecimal getAmount() { - return this.amount; - } - - public LocalDate getTransactionDate() { - LocalDate transactionDate = null; - if (this.transactionDate != null) { - transactionDate = new LocalDate(this.transactionDate); - } - return transactionDate; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingScheduleInstallments.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingScheduleInstallments.java deleted file mode 100644 index 3c94fc144..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/domain/SavingScheduleInstallments.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.domain; - -import java.math.BigDecimal; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom; -import org.mifosplatform.useradministration.domain.AppUser; - -@Entity -@Table(name = "m_saving_schedule") -public class SavingScheduleInstallments extends AbstractAuditableCustom { - - @SuppressWarnings("unused") - @ManyToOne(optional = false) - @JoinColumn(name = "saving_account_id", nullable = false) - private SavingAccount savingAccount; - - @Temporal(TemporalType.DATE) - @Column(name = "duedate", nullable = false) - private final Date dueDate; - - @SuppressWarnings("unused") - @Column(name = "installment", nullable = false) - private final Integer installmentNumber; - - @Column(name = "deposit", scale = 6, precision = 19, nullable = false) - private BigDecimal deposit; - - @Temporal(TemporalType.DATE) - @Column(name = "payment_date", nullable = true) - private Date paymentDate; - - @Column(name = "deposit_paid", scale = 6, precision = 19, nullable = true) - private BigDecimal depositPaid; - - @SuppressWarnings("unused") - @Column(name = "interest_accured", scale = 6, precision = 19, nullable = true) - private BigDecimal interstAccured; - - @Column(name = "completed_derived", nullable = false) - private boolean completed; - - public SavingScheduleInstallments() { - this.dueDate = null; - this.installmentNumber = null; - this.paymentDate = null; - } - - public SavingScheduleInstallments(SavingAccount account, Date dueDate, Integer installmentNumber, BigDecimal deposit, - BigDecimal interstAccured) { - this.savingAccount = account; - this.dueDate = dueDate; - this.installmentNumber = installmentNumber; - this.deposit = deposit; - this.paymentDate = null; - this.depositPaid = BigDecimal.ZERO; - this.completed = false; - this.interstAccured = interstAccured; - } - - public void updateAccount(SavingAccount account) { - this.savingAccount = account; - } - - public Date getPaymentDate() { - return this.paymentDate; - } - - public void setPaymentDate(Date paymentDate) { - this.paymentDate = paymentDate; - } - - public BigDecimal getDepositPaid() { - return this.depositPaid; - } - - public void setDepositPaid(BigDecimal depositPaid) { - this.depositPaid = depositPaid; - } - - public Date getDueDate() { - return this.dueDate; - } - - public BigDecimal getDeposit() { - return this.deposit; - } - - public boolean isCompleted() { - return this.completed; - } - - public void setCompleted(boolean completed) { - this.completed = completed; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/exception/SavingAccountNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/exception/SavingAccountNotFoundException.java deleted file mode 100644 index 1cca0da91..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/exception/SavingAccountNotFoundException.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.exception; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - -public class SavingAccountNotFoundException extends AbstractPlatformResourceNotFoundException { - - public SavingAccountNotFoundException(final Long id) { - super("error.msg.saving.account.id.invalid", "Saving account with identifier " + id + " does not exist", id); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/ApproveSavingAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/ApproveSavingAccountCommandHandler.java deleted file mode 100644 index 8d30c8727..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/ApproveSavingAccountCommandHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ApproveSavingAccountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public ApproveSavingAccountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.approveSavingAccount(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/CreateSavingAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/CreateSavingAccountCommandHandler.java deleted file mode 100644 index 56dfd9dcf..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/CreateSavingAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class CreateSavingAccountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public CreateSavingAccountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.createSavingAccount(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DeleteSavingAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DeleteSavingAccountCommandHandler.java deleted file mode 100644 index 3755b6824..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DeleteSavingAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class DeleteSavingAccountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public DeleteSavingAccountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.deleteSavingAccount(command.entityId()); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DepositSavingAmountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DepositSavingAmountCommandHandler.java deleted file mode 100644 index bf5579376..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/DepositSavingAmountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class DepositSavingAmountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public DepositSavingAmountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.depositMoney(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/RejectSavingAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/RejectSavingAccountCommandHandler.java deleted file mode 100644 index dca553e24..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/RejectSavingAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class RejectSavingAccountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public RejectSavingAccountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.rejectSavingApplication(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UndoApprovalSavingAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UndoApprovalSavingAccountCommandHandler.java deleted file mode 100644 index 4f9bda0a0..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UndoApprovalSavingAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UndoApprovalSavingAccountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public UndoApprovalSavingAccountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.undoSavingAccountApproval(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UpdateSavingAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UpdateSavingAccountCommandHandler.java deleted file mode 100644 index cd95421cf..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/UpdateSavingAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UpdateSavingAccountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public UpdateSavingAccountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.updateSavingAccount(command.entityId(), command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingAmountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingAmountCommandHandler.java deleted file mode 100644 index 24212f3dd..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingAmountCommandHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class WithdrawSavingAmountCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public WithdrawSavingAmountCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.withdrawSavingAmount(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingApplicationCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingApplicationCommandHandler.java deleted file mode 100644 index 7f6cffdb8..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/handler/WithdrawSavingApplicationCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.service.SavingAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class WithdrawSavingApplicationCommandHandler implements NewCommandSourceHandler { - - private final SavingAccountWritePlatformService savingAccountWritePlatformService; - - @Autowired - public WithdrawSavingApplicationCommandHandler(final SavingAccountWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.savingAccountWritePlatformService.withdrawSavingApplication(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/CalculateSavingScheduleQueryFromApiJsonHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/CalculateSavingScheduleQueryFromApiJsonHelper.java deleted file mode 100644 index c258fa80f..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/CalculateSavingScheduleQueryFromApiJsonHelper.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public final class CalculateSavingScheduleQueryFromApiJsonHelper { - - final Set supportedParams = new HashSet(Arrays.asList("clientId", "productId", "externalId", - "savingsDepositAmountPerPeriod", "recurringInterestRate", "savingInterestRate", "tenure", "commencementDate", "locale", - "dateFormat", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "tenureType", "frequency", "interestType", - "interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "depositEvery", "interestPostEvery", - "interestPostFrequency")); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public CalculateSavingScheduleQueryFromApiJsonHelper(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("saving.account"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).notNull(); - - final BigDecimal savingsDepositAmountPerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - "savingsDepositAmountPerPeriod", element); - baseDataValidator.reset().parameter("savingsDepositAmountPerPeriod").value(savingsDepositAmountPerPeriod).notNull() - .zeroOrPositiveAmount(); - - final BigDecimal recurringInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("recurringInterestRate", element); - baseDataValidator.reset().parameter("recurringInterestRate").value(recurringInterestRate).notNull().zeroOrPositiveAmount(); - - final BigDecimal savingInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingInterestRate", element); - baseDataValidator.reset().parameter("savingInterestRate").value(savingInterestRate).notNull().zeroOrPositiveAmount(); - - final Integer tenure = fromApiJsonHelper.extractIntegerNamed("tenure", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenure").value(tenure).notNull(); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).notNull(); - - final Boolean isLockinPeriodAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(isLockinPeriodAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).notNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).notNull().inMinMaxRange(1, 3); - - final Integer tenureType = fromApiJsonHelper.extractIntegerNamed("tenureType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureType").value(tenureType).ignoreIfNull(); - - final Integer frequency = fromApiJsonHelper.extractIntegerNamed("frequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("frequency").value(frequency).ignoreIfNull(); - - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestType").value(interestType).ignoreIfNull(); - - final Integer interestCalculationMethod = fromApiJsonHelper.extractIntegerNamed("interestCalculationMethod", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCalculationMethod").value(interestCalculationMethod).ignoreIfNull(); - - final BigDecimal minimumBalanceForWithdrawal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minimumBalanceForWithdrawal", - element); - baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(minimumBalanceForWithdrawal).ignoreIfNull() - .zeroOrPositiveAmount(); - - final Boolean isPartialDepositAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isPartialDepositAllowed", element); - baseDataValidator.reset().parameter("isPartialDepositAllowed").value(isPartialDepositAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isPartialDepositAllowedCommandValue)).ignoreIfNull(); - - final Integer depositEvery = fromApiJsonHelper.extractIntegerNamed("depositEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("depositEvery").value(depositEvery).notNull().zeroOrPositiveAmount(); - - final Integer interestPostEvery = fromApiJsonHelper.extractIntegerNamed("interestPostEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestPostEvery").value(interestPostEvery).notNull().zeroOrPositiveAmount(); - - final Integer interestPostFrequency = fromApiJsonHelper.extractIntegerNamed("interestPostFrequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestPostFrequency").value(interestPostFrequency).notNull().zeroOrPositiveAmount(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - private Boolean isBooleanValueUpdated(final Boolean actualValue) { - Boolean isUpdated = false; - if (actualValue != null) { - isUpdated = true; - } - return isUpdated; - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountCommandFromApiJsonDeserializer.java deleted file mode 100644 index 021937f6d..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountCommandFromApiJsonDeserializer.java +++ /dev/null @@ -1,216 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public class SavingAccountCommandFromApiJsonDeserializer { - - final Set supportedParams = new HashSet(Arrays.asList("clientId", "productId", "externalId", "currencyCode", - "digitsAfterDecimal", "savingsDepositAmountPerPeriod", "recurringInterestRate", "savingInterestRate", "tenure", - "commencementDate", "locale", "dateFormat", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "tenureType", - "frequency", "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", - "depositEvery", "interestPostEvery", "interestPostFrequency")); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public SavingAccountCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForCreate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("saving.account"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - baseDataValidator.reset().parameter("clientId").value(clientId).notNull(); - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).notNull(); - - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).ignoreIfNull().notExceedingLengthOf(100); - - final BigDecimal savingsDepositAmountPerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - "savingsDepositAmountPerPeriod", element); - baseDataValidator.reset().parameter("savingsDepositAmountPerPeriod").value(savingsDepositAmountPerPeriod).notNull() - .zeroOrPositiveAmount(); - - final BigDecimal recurringInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("recurringInterestRate", element); - baseDataValidator.reset().parameter("recurringInterestRate").value(recurringInterestRate).notNull().zeroOrPositiveAmount(); - - final BigDecimal savingInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingInterestRate", element); - baseDataValidator.reset().parameter("savingInterestRate").value(savingInterestRate).notNull().zeroOrPositiveAmount(); - - final Integer tenure = fromApiJsonHelper.extractIntegerNamed("tenure", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenure").value(tenure).notNull(); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).notNull(); - - final Boolean isLockinPeriodAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(isLockinPeriodAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).notNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).notNull().inMinMaxRange(1, 3); - - final Integer tenureType = fromApiJsonHelper.extractIntegerNamed("tenureType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureType").value(tenureType).ignoreIfNull(); - - final Integer frequency = fromApiJsonHelper.extractIntegerNamed("frequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("frequency").value(frequency).ignoreIfNull(); - - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestType").value(interestType).ignoreIfNull(); - - final Integer interestCalculationMethod = fromApiJsonHelper.extractIntegerNamed("interestCalculationMethod", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCalculationMethod").value(interestCalculationMethod).ignoreIfNull(); - - final BigDecimal minimumBalanceForWithdrawal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minimumBalanceForWithdrawal", - element); - baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(minimumBalanceForWithdrawal).ignoreIfNull() - .zeroOrPositiveAmount(); - - final Boolean isPartialDepositAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isPartialDepositAllowed", element); - baseDataValidator.reset().parameter("isPartialDepositAllowed").value(isPartialDepositAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isPartialDepositAllowedCommandValue)).ignoreIfNull(); - - final Integer depositEvery = fromApiJsonHelper.extractIntegerNamed("depositEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("depositEvery").value(depositEvery).notNull().zeroOrPositiveAmount(); - - final Integer interestPostEvery = fromApiJsonHelper.extractIntegerNamed("interestPostEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestPostEvery").value(interestPostEvery).notNull().zeroOrPositiveAmount(); - - final Integer interestPostFrequency = fromApiJsonHelper.extractIntegerNamed("interestPostFrequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestPostFrequency").value(interestPostFrequency).notNull().zeroOrPositiveAmount(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForUpdate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("saving.account"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).ignoreIfNull(); - - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).ignoreIfNull().notExceedingLengthOf(100); - - final BigDecimal savingsDepositAmountPerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - "savingsDepositAmountPerPeriod", element); - baseDataValidator.reset().parameter("savingsDepositAmountPerPeriod").value(savingsDepositAmountPerPeriod).ignoreIfNull() - .zeroOrPositiveAmount(); - - final BigDecimal recurringInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("recurringInterestRate", element); - baseDataValidator.reset().parameter("recurringInterestRate").value(recurringInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal savingInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingInterestRate", element); - baseDataValidator.reset().parameter("savingInterestRate").value(savingInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer tenure = fromApiJsonHelper.extractIntegerNamed("tenure", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenure").value(tenure).ignoreIfNull(); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).ignoreIfNull(); - - final Boolean isLockinPeriodAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(isLockinPeriodAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - final Integer tenureType = fromApiJsonHelper.extractIntegerNamed("tenureType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureType").value(tenureType).ignoreIfNull(); - - final Integer frequency = fromApiJsonHelper.extractIntegerNamed("frequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("frequency").value(frequency).ignoreIfNull(); - - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestType").value(interestType).ignoreIfNull(); - - final Integer interestCalculationMethod = fromApiJsonHelper.extractIntegerNamed("interestCalculationMethod", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCalculationMethod").value(interestCalculationMethod).ignoreIfNull(); - - final BigDecimal minimumBalanceForWithdrawal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minimumBalanceForWithdrawal", - element); - baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(minimumBalanceForWithdrawal).ignoreIfNull() - .zeroOrPositiveAmount(); - - final Boolean isPartialDepositAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isPartialDepositAllowed", element); - baseDataValidator.reset().parameter("isPartialDepositAllowed").value(isPartialDepositAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isPartialDepositAllowedCommandValue)).ignoreIfNull(); - - final Integer depositEvery = fromApiJsonHelper.extractIntegerNamed("depositEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("depositEvery").value(depositEvery).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer interestPostEvery = fromApiJsonHelper.extractIntegerNamed("interestPostEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestPostEvery").value(interestPostEvery).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer interestPostFrequency = fromApiJsonHelper.extractIntegerNamed("interestPostFrequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestPostFrequency").value(interestPostFrequency).ignoreIfNull().zeroOrPositiveAmount(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - - private Boolean isBooleanValueUpdated(final Boolean actualValue) { - Boolean isUpdated = false; - if (actualValue != null) { - isUpdated = true; - } - return isUpdated; - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountStateTransitionCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountStateTransitionCommandFromApiJsonDeserializer.java deleted file mode 100644 index ff8f47a14..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/serialization/SavingAccountStateTransitionCommandFromApiJsonDeserializer.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public class SavingAccountStateTransitionCommandFromApiJsonDeserializer { - - private final Set supportedParams = new HashSet(Arrays.asList("locale", "dateFormat", "commencementDate", "eventDate", - "savingsDepositAmountPerPeriod", "minimumBalanceForWithdrawal", "recurringInterestRate", "savingInterestRate", "depositDate", - "interestType", "tenure", "tenureType", "frequency", "payEvery", "note", "interestPostEvery", "interestPostFrequency")); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public SavingAccountStateTransitionCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForApprove(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("saving.account.transition"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).notNull(); - - final BigDecimal savingsDepositAmountPerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - "savingsDepositAmountPerPeriod", element); - baseDataValidator.reset().parameter("savingsDepositAmountPerPeriod").value(savingsDepositAmountPerPeriod).ignoreIfNull() - .zeroOrPositiveAmount(); - - final BigDecimal minimumBalanceForWithdrawal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minimumBalanceForWithdrawal", - element); - baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(minimumBalanceForWithdrawal).ignoreIfNull() - .zeroOrPositiveAmount(); - - final BigDecimal recurringInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("recurringInterestRate", element); - baseDataValidator.reset().parameter("recurringInterestRate").value(recurringInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal savingInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingInterestRate", element); - baseDataValidator.reset().parameter("savingInterestRate").value(savingInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestType").value(interestType).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer tenureType = fromApiJsonHelper.extractIntegerNamed("tenureType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureType").value(tenureType).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer tenure = fromApiJsonHelper.extractIntegerNamed("tenure", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenure").value(tenure).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer frequency = fromApiJsonHelper.extractIntegerNamed("frequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("frequency").value(frequency).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer depositEvery = fromApiJsonHelper.extractIntegerNamed("payEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("payEvery").value(depositEvery).ignoreIfNull().zeroOrPositiveAmount(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForReject(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("saving.account.transition"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate eventDate = fromApiJsonHelper.extractLocalDateNamed("eventDate", element); - baseDataValidator.reset().parameter("eventDate").value(eventDate).notNull(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForWithdrawApplication(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("saving.account.transition"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate eventDate = fromApiJsonHelper.extractLocalDateNamed("eventDate", element); - baseDataValidator.reset().parameter("eventDate").value(eventDate).notNull(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForDepositAmount(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("saving.account.transaction.deposit"); - - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate depositDate = fromApiJsonHelper.extractLocalDateNamed("depositDate", element); - baseDataValidator.reset().parameter("depositDate").value(depositDate).notNull(); - - final BigDecimal savingsDepositAmountPerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - "savingsDepositAmountPerPeriod", element); - baseDataValidator.reset().parameter("savingsDepositAmountPerPeriod").value(savingsDepositAmountPerPeriod).notNull() - .zeroOrPositiveAmount(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingSchedule.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingSchedule.java deleted file mode 100644 index 8efa1367b..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingSchedule.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import org.mifosplatform.infrastructure.core.api.JsonQuery; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; - -public interface CalculateSavingSchedule { - SavingScheduleData calculateSavingSchedule(JsonQuery query); -} - diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingScheduleImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingScheduleImpl.java deleted file mode 100644 index 59541ad23..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/CalculateSavingScheduleImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import org.mifosplatform.infrastructure.core.api.JsonQuery; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; -import org.mifosplatform.portfolio.savingsaccount.serialization.CalculateSavingScheduleQueryFromApiJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class CalculateSavingScheduleImpl implements CalculateSavingSchedule { - - private final PlatformSecurityContext context; - private final CalculateSavingScheduleQueryFromApiJsonHelper fromApiJsonDeserializer; - private final SavingScheduleAssembler savingScheduleAssembler; - - @Autowired - public CalculateSavingScheduleImpl(final PlatformSecurityContext context, - final CalculateSavingScheduleQueryFromApiJsonHelper fromApiJsonDeserializer, - final SavingScheduleAssembler savingScheduleAssembler) { - this.context = context; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; - this.savingScheduleAssembler = savingScheduleAssembler; - } - - @Override - public SavingScheduleData calculateSavingSchedule(final JsonQuery query) { - - context.authenticatedUser(); - - this.fromApiJsonDeserializer.validate(query.json()); - - return this.savingScheduleAssembler.fromJson(query.parsedJson()); - - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/DefaultDepositScheduleDateGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/DefaultDepositScheduleDateGenerator.java deleted file mode 100644 index 573c4574c..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/DefaultDepositScheduleDateGenerator.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.util.ArrayList; -import java.util.List; - -import org.joda.time.LocalDate; -import org.mifosplatform.portfolio.savingsaccount.domain.DepositScheduleDateGenerator; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; - -public class DefaultDepositScheduleDateGenerator implements DepositScheduleDateGenerator { - - @Override - public List generate(LocalDate scheuleStartDate, Integer paymentPeriods, Integer depositFrequency, - SavingFrequencyType savingFrequencyType) { - - List duePaymentPeriodDates = new ArrayList(depositFrequency); - LocalDate startDate = scheuleStartDate; - - for (int period = 1; period <= paymentPeriods; period++) { - - LocalDate duePaymentPeriodDate = startDate; - if (period == 1) { - duePaymentPeriodDate = startDate; - } else { - switch (savingFrequencyType) { - case DAILY: - duePaymentPeriodDate = startDate.plusDays(depositFrequency); - break; - case MONTHLY: - duePaymentPeriodDate = startDate.plusMonths(depositFrequency); - break; - case QUATERLY: - duePaymentPeriodDate = startDate.plusMonths(3*depositFrequency); - break; - case HALFYEARLY: - duePaymentPeriodDate = startDate.plusMonths(6*depositFrequency); - break; - case YEARLY: - duePaymentPeriodDate = startDate.plusYears(depositFrequency); - break; - default: - break; - } - } - duePaymentPeriodDates.add(duePaymentPeriodDate); - startDate = duePaymentPeriodDate; - } - - return duePaymentPeriodDates; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountAssembler.java deleted file mode 100644 index 8c8c201e6..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountAssembler.java +++ /dev/null @@ -1,512 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.client.domain.Client; -import org.mifosplatform.portfolio.client.domain.ClientRepository; -import org.mifosplatform.portfolio.client.exception.ClientNotFoundException; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingSchedulePeriodData; -import org.mifosplatform.portfolio.savingsaccount.domain.ReccuringDepositInterestCalculator; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccount; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingScheduleInstallments; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductRepository; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsaccountproduct.exception.SavingProductNotFoundException; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountStatus; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachine; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachineImpl; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccountTransactionsException; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.google.gson.JsonElement; - -@Service -public class SavingAccountAssembler { - - private final ClientRepository clientRepository; - private final SavingProductRepository savingProductRepository; - private final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator; - private final FromJsonHelper fromApiJsonHelper; - private final SavingScheduleAssembler savingScheduleAssembler; - - @Autowired - public SavingAccountAssembler(final ClientRepository clientRepository, final SavingProductRepository savingProductRepository, - final ReccuringDepositInterestCalculator reccuringDepositInterestCalculator, final FromJsonHelper fromApiJsonHelper, - final SavingScheduleAssembler savingScheduleAssembler) { - this.clientRepository = clientRepository; - this.savingProductRepository = savingProductRepository; - this.reccuringDepositInterestCalculator = reccuringDepositInterestCalculator; - this.fromApiJsonHelper = fromApiJsonHelper; - this.savingScheduleAssembler = savingScheduleAssembler; - } - - public SavingAccount assembleFrom(final JsonCommand command) { - - final JsonElement element = command.parsedJson(); - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); - final Integer digitsAfterDecimal = command.integerValueOfParameterNamed("digitsAfterDecimal"); - final BigDecimal savingsDepositAmountPerPeriod = command.bigDecimalValueOfParameterNamed("savingsDepositAmountPerPeriod"); - final BigDecimal recurringInterestRate = command.bigDecimalValueOfParameterNamed("recurringInterestRate"); - final BigDecimal savingInterestRateCommandValue = command.bigDecimalValueOfParameterNamed("savingInterestRate"); - final Integer tenureCommandValue = command.integerValueOfParameterNamed("tenure"); - final LocalDate commencementDate = command.localDateValueOfParameterNamed("commencementDate"); - final Integer lockinPeriodTypeCommandValue = command.integerValueOfParameterNamed("lockinPeriodType"); - final boolean isLockinPeriodAllowedCommandValue = command.booleanPrimitiveValueOfParameterNamed("isLockinPeriodAllowed"); - final Integer lockinPeriodCommandValue = command.integerValueOfParameterNamed("lockinPeriod"); - final Integer tenureTypeCommandValue = command.integerValueOfParameterNamed("tenureType"); - final Integer frequencyCommandValue = command.integerValueOfParameterNamed("frequency"); - final Integer interestTypeCommandValue = command.integerValueOfParameterNamed("interestType"); - final Integer interestCalculationMethodCommandValue = command.integerValueOfParameterNamed("interestCalculationMethod"); - // final BigDecimal minimumBalanceForWithdrawal = - // command.bigDecimalValueOfParameterNamed("minimumBalanceForWithdrawal"); - // final boolean isPartialDepositAllowed = - // command.booleanPrimitiveValueOfParameterNamed("isPartialDepositAllowed"); - final Integer depositEvery = command.integerValueOfParameterNamed("depositEvery"); - final Integer interestPostEvery = command.integerValueOfParameterNamed("interestPostEvery"); - final Integer interestPostFrequencyCommandValue = command.integerValueOfParameterNamed("interestPostFrequency"); - - Client client = this.clientRepository.findOne(clientId); - if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } - - SavingProduct product = this.savingProductRepository.findOne(productId); - if (product == null || product.isDeleted()) { throw new SavingProductNotFoundException(productId); } - - MonetaryCurrency currency = product.getCurrency(); - if (currencyCode != null) currency = new MonetaryCurrency(currencyCode, currency.getDigitsAfterDecimal()); - if (digitsAfterDecimal != null) currency = new MonetaryCurrency(currency.getCode(), digitsAfterDecimal); - - Money savingsDeposit = Money.of(currency, product.getSavingProductRelatedDetail().getSavingsDepositAmount()); - if (savingsDepositAmountPerPeriod != null) { - savingsDeposit = Money.of(currency, savingsDepositAmountPerPeriod); - } - - Integer tenure = product.getSavingProductRelatedDetail().getTenure(); - if (tenureCommandValue != null) { - tenure = tenureCommandValue; - } - - TenureTypeEnum tenureTypeEnum = TenureTypeEnum.fromInt(product.getSavingProductRelatedDetail().getTenureType()); - if (tenureTypeCommandValue != null) { - tenureTypeEnum = TenureTypeEnum.fromInt(tenureTypeCommandValue); - } - - SavingProductType savingProductType = SavingProductType.fromInt(product.getSavingProductRelatedDetail().getSavingProductType()); - - SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(product.getSavingProductRelatedDetail().getFrequency()); - if (frequencyCommandValue != null) { - savingFrequencyType = SavingFrequencyType.fromInt(frequencyCommandValue); - } - - SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(product - .getSavingProductRelatedDetail().getInterestCalculationMethod()); - if (interestCalculationMethodCommandValue != null) { - savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(interestCalculationMethodCommandValue); - } - - SavingsInterestType interestType = SavingsInterestType.fromInt(product.getSavingProductRelatedDetail().getInterestType()); - if (interestTypeCommandValue != null) { - interestType = SavingsInterestType.fromInt(interestTypeCommandValue); - } - - BigDecimal savingInterestRate = product.getInterestRate(); - if (savingInterestRateCommandValue != null) savingInterestRate = savingInterestRateCommandValue; - - boolean isLockinPeriodAllowed = product.getSavingProductRelatedDetail().isLockinPeriodAllowed(); - if (isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)) { - isLockinPeriodAllowed = isLockinPeriodAllowedCommandValue; - } - - Integer lockinPeriod = product.getSavingProductRelatedDetail().getLockinPeriod(); - if (lockinPeriodCommandValue != null) { - lockinPeriod = lockinPeriodCommandValue; - } - - PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(product.getSavingProductRelatedDetail().getLockinPeriodType()); - if (lockinPeriodTypeCommandValue != null) { - lockinPeriodType = PeriodFrequencyType.fromInt(lockinPeriodTypeCommandValue); - } - - Integer interestPostFrequency = PeriodFrequencyType.fromInt(interestPostFrequencyCommandValue).getValue(); - - SavingAccount account = SavingAccount.openNew(client, product, externalId, savingsDeposit, recurringInterestRate, - savingInterestRate, tenure, commencementDate, tenureTypeEnum, savingProductType, savingFrequencyType, interestType, - savingInterestCalculationMethod, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, - this.reccuringDepositInterestCalculator, defaultDepositLifecycleStateMachine(), depositEvery, interestPostEvery, - interestPostFrequency); - - SavingScheduleData savingScheduleData = this.savingScheduleAssembler.fromJson(element); - for (SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()) { - - final SavingScheduleInstallments installment = new SavingScheduleInstallments(account, savingSchedulePeriodData.getDueDate() - .toDate(), savingSchedulePeriodData.getPeriod(), savingSchedulePeriodData.getDepositDue(), - savingSchedulePeriodData.getInterestAccured()); - account.addSavingScheduleInstallment(installment); - } - - return account; - } - - public Map assembleFrom(final JsonCommand command, final SavingAccount account) { - - JsonElement element = command.parsedJson(); - Map actualChanges = new LinkedHashMap(20); - final String localeAsInput = command.locale(); - - SavingProduct product = account.getProduct(); - final String productIdParamName = "productId"; - if (command.isChangeInLongParameterNamed(productIdParamName, product.getId())) { - final Long newValue = command.longValueOfParameterNamed(productIdParamName); - if (newValue != null) { - product = this.savingProductRepository.findOne(newValue); - actualChanges.put("productId", newValue); - if (product == null || product.isDeleted()) throw new SavingProductNotFoundException(newValue); - } - } - - String externalId = account.getExternalId(); - final String externalIdParamName = "externalId"; - if (command.isChangeInStringParameterNamed(externalIdParamName, externalId)) { - final String newValue = command.stringValueOfParameterNamed(externalIdParamName); - actualChanges.put(externalIdParamName, newValue); - externalId = newValue; - } - - Money savingsDeposit = Money.of(product.getCurrency(), account.getSavingsDepositAmountPerPeriod()); - - final String savingsDepositAmountPerPeriodParamName = "savingsDepositAmountPerPeriod"; - if (command.isChangeInBigDecimalParameterNamed(savingsDepositAmountPerPeriodParamName, savingsDeposit.getAmount())) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(savingsDepositAmountPerPeriodParamName); - actualChanges.put(savingsDepositAmountPerPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - savingsDeposit = Money.of(savingsDeposit.getCurrency(), newValue); - } - - Integer tenure = account.getTenure(); - final String tenureParamName = "tenure"; - if (command.isChangeInIntegerParameterNamed(tenureParamName, tenure)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureParamName); - actualChanges.put(tenureParamName, newValue); - actualChanges.put("locale", localeAsInput); - tenure = newValue; - } - - LocalDate commencementDate = new LocalDate(account.getProjectedCommencementDate()); - final String commencementDateParamName = "commencementDate"; - if (command.isChangeInLocalDateParameterNamed("commencementDate", commencementDate)) { - final LocalDate newValue = command.localDateValueOfParameterNamed(commencementDateParamName); - actualChanges.put(commencementDateParamName, newValue); - commencementDate = newValue; - } - - TenureTypeEnum tenureTypeEnum = TenureTypeEnum.fromInt(account.getTenureType()); - final String tenureTypeParamName = "tenureType"; - if (command.isChangeInIntegerParameterNamed(tenureTypeParamName, tenureTypeEnum.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(tenureTypeParamName); - actualChanges.put(tenureTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - tenureTypeEnum = TenureTypeEnum.fromInt(newValue); - } - - SavingProductType savingProductType = SavingProductType.fromInt(account.getSavingProductType()); - - SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(account.getFrequency()); - final String frequencyParamName = "frequency"; - if (command.isChangeInIntegerParameterNamed(frequencyParamName, savingFrequencyType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(frequencyParamName); - actualChanges.put(frequencyParamName, newValue); - actualChanges.put("locale", localeAsInput); - savingFrequencyType = SavingFrequencyType.fromInt(newValue); - } - - SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(account - .getInterestCalculationMethod()); - final String interestCalculationMethodParamName = "interestCalculationMethod"; - if (command.isChangeInIntegerParameterNamed(interestCalculationMethodParamName, savingInterestCalculationMethod.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(interestCalculationMethodParamName); - actualChanges.put(interestCalculationMethodParamName, newValue); - actualChanges.put("locale", localeAsInput); - savingInterestCalculationMethod = SavingInterestCalculationMethod.fromInt(newValue); - } - - BigDecimal reccuringInterestRate = account.getReccuringInterestRate(); - final String reccuringInterestRateParamName = "reccuringInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(reccuringInterestRateParamName, reccuringInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(reccuringInterestRateParamName); - actualChanges.put(reccuringInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - reccuringInterestRate = newValue; - } - - BigDecimal savingInterestRate = account.getSavingInterestRate(); - final String savingInterestRateParamName = "savingInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(savingInterestRateParamName, savingInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(savingInterestRateParamName); - actualChanges.put(savingInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - savingInterestRate = newValue; - } - - Boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); - final String isLockinPeriodAllowedParamName = "isLockinPeriodAllowed"; - if (command.isChangeInBooleanParameterNamed(isLockinPeriodAllowedParamName, isLockinPeriodAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isLockinPeriodAllowedParamName); - actualChanges.put(isLockinPeriodAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - isLockinPeriodAllowed = newValue; - } - - Integer lockinPeriod = account.getLockinPeriod(); - final String lockinPeriodParamName = "lockinPeriod"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodParamName, lockinPeriod)) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodParamName); - actualChanges.put(lockinPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - lockinPeriod = newValue; - } - - PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(account.getLockinPeriodType()); - final String lockinPeriodTypeParamName = "lockinPeriodType"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodTypeParamName, lockinPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodTypeParamName); - actualChanges.put(lockinPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - lockinPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - Integer payEvery = account.getPayEvery(); - final String depositEveryParamName = "depositEvery"; - if (command.isChangeInIntegerParameterNamed(depositEveryParamName, payEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(depositEveryParamName); - actualChanges.put(depositEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - payEvery = newValue; - } - - SavingsInterestType interestType = SavingsInterestType.fromInt(product.getSavingProductRelatedDetail().getInterestType()); - final String interestTypeParamName = "interestType"; - if (command.isChangeInIntegerParameterNamed(interestTypeParamName, interestType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(interestTypeParamName); - actualChanges.put(interestTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestType = SavingsInterestType.fromInt(newValue); - } - - Integer interestPostEvery = account.getInterestPostEvery(); - final String interestPostEveryParamName = "interestPostEvery"; - if (command.isChangeInIntegerParameterNamed(interestPostEveryParamName, interestPostEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(interestPostEveryParamName); - actualChanges.put(interestPostEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestPostEvery = newValue; - } - - Integer interestPostFrequency = account.getInterestPostFrequency(); - final String interestPostFrequencyParamName = "interestPostFrequency"; - if (command.isChangeInIntegerParameterNamed(interestPostFrequencyParamName, interestPostFrequency)) { - final Integer newValue = command.integerValueOfParameterNamed(interestPostFrequencyParamName); - actualChanges.put(interestPostFrequencyParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestPostFrequency = PeriodFrequencyType.fromInt(newValue).getValue(); - } - - account.modifyAccount(product, externalId, savingsDeposit, reccuringInterestRate, savingInterestRate, tenure, commencementDate, - tenureTypeEnum, savingProductType, savingFrequencyType, savingInterestCalculationMethod, isLockinPeriodAllowed, - lockinPeriod, lockinPeriodType, this.reccuringDepositInterestCalculator, payEvery, interestType, interestPostEvery, - interestPostFrequency); - - SavingScheduleData savingScheduleData = this.savingScheduleAssembler.fromJson(element); - for (SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()) { - - final SavingScheduleInstallments installment = new SavingScheduleInstallments(account, savingSchedulePeriodData.getDueDate() - .toDate(), savingSchedulePeriodData.getPeriod(), savingSchedulePeriodData.getDepositDue(), - savingSchedulePeriodData.getInterestAccured()); - account.addSavingScheduleInstallment(installment); - } - - return actualChanges; - - } - - private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() { - List allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values()); - return new DepositLifecycleStateMachineImpl(allowedDepositStatuses); - } - - public Map approveSavingAccount(final JsonCommand command, final SavingAccount account) { - - JsonElement element = command.parsedJson(); - Map actualChanges = new LinkedHashMap(20); - final String localeAsInput = command.locale(); - - LocalDate approvalDate = account.projectedCommencementDate(); - final String commencementDateParamName = "commencementDate"; - if (command.isChangeInLocalDateParameterNamed("commencementDate", approvalDate)) { - final LocalDate newValue = command.localDateValueOfParameterNamed(commencementDateParamName); - actualChanges.put(commencementDateParamName, newValue); - approvalDate = newValue; - } - - BigDecimal savingsDepositAmountPerPeriod = account.getSavingsDepositAmountPerPeriod(); - final String savingsDepositAmountPerPeriodParamName = "savingsDepositAmountPerPeriod"; - if (command.isChangeInBigDecimalParameterNamed(savingsDepositAmountPerPeriodParamName, savingsDepositAmountPerPeriod)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(savingsDepositAmountPerPeriodParamName); - actualChanges.put(savingsDepositAmountPerPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - savingsDepositAmountPerPeriod = newValue; - } - - BigDecimal recurringInterestRate = account.getReccuringInterestRate(); - final String reccuringInterestRateParamName = "reccuringInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(reccuringInterestRateParamName, recurringInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(reccuringInterestRateParamName); - actualChanges.put(reccuringInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - recurringInterestRate = newValue; - } - - BigDecimal savingInterestRate = account.getSavingInterestRate(); - final String savingInterestRateParamName = "savingInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(savingInterestRateParamName, savingInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(savingInterestRateParamName); - actualChanges.put(savingInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - savingInterestRate = newValue; - } - - Integer interestType = account.getInterestType(); - final String interestTypeParamName = "interestType"; - if (command.isChangeInIntegerParameterNamed(interestTypeParamName, interestType)) { - final Integer newValue = command.integerValueOfParameterNamed(interestTypeParamName); - actualChanges.put(interestTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestType = SavingsInterestType.fromInt(newValue).getValue(); - } - - Integer tenure = account.getTenure(); - final String tenureParamName = "tenure"; - if (command.isChangeInIntegerParameterNamed(tenureParamName, tenure)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureParamName); - actualChanges.put(tenureParamName, newValue); - actualChanges.put("locale", localeAsInput); - tenure = newValue; - } - - Integer tenureType = account.getTenureType(); - final String tenureTypeParamName = "tenureType"; - if (command.isChangeInIntegerParameterNamed(tenureTypeParamName, tenureType)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureTypeParamName); - actualChanges.put(tenureTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - tenureType = TenureTypeEnum.fromInt(newValue).getValue(); - } - - Integer frequency = account.getFrequency(); - final String frequencyParamName = "frequency"; - if (command.isChangeInIntegerParameterNamed(frequencyParamName, frequency)) { - final Integer newValue = command.integerValueOfParameterNamed(frequencyParamName); - actualChanges.put(frequencyParamName, newValue); - actualChanges.put("locale", localeAsInput); - frequency = SavingFrequencyType.fromInt(newValue).getValue(); - } - - Integer depositEvery = account.getPayEvery(); - final String depositEveryParamName = "depositEvery"; - if (command.isChangeInIntegerParameterNamed(depositEveryParamName, depositEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(depositEveryParamName); - actualChanges.put(depositEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - depositEvery = newValue; - } - - Integer interestPostEvery = account.getInterestPostEvery(); - final String interestPostEveryParamName = "interestPostEvery"; - if (command.isChangeInIntegerParameterNamed(interestPostEveryParamName, interestPostEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(interestPostEveryParamName); - actualChanges.put(interestPostEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestPostEvery = newValue; - } - - Integer interestPostFrequency = account.getInterestPostFrequency(); - final String interestPostFrequencyParamName = "interestPostFrequency"; - if (command.isChangeInIntegerParameterNamed(interestPostFrequencyParamName, interestPostFrequency)) { - final Integer newValue = command.integerValueOfParameterNamed(interestPostFrequencyParamName); - actualChanges.put(interestPostFrequencyParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestPostFrequency = PeriodFrequencyType.fromInt(newValue).getValue(); - } - - account.approveSavingAccount(approvalDate, savingsDepositAmountPerPeriod, recurringInterestRate, savingInterestRate, interestType, - tenure, tenureType, frequency, depositEvery, defaultDepositLifecycleStateMachine(), - this.reccuringDepositInterestCalculator, interestPostEvery, interestPostFrequency); - - /* - * CalculateSavingScheduleCommand calculateSavingScheduleCommand = new - * CalculateSavingScheduleCommand(account.getProduct().getId(), - * savingsDepositAmountPerPeriod, payEvery, frequency, - * recurringInterestRate, approvalDate, - * tenure,tenureType,interestPostEvery - * ,interestPostFrequency,account.getInterestCalculationMethod()); - */ - - SavingScheduleData savingScheduleData = this.savingScheduleAssembler.calculateSavingSchedule(element, account); - for (SavingSchedulePeriodData savingSchedulePeriodData : savingScheduleData.getPeriods()) { - - final SavingScheduleInstallments installment = new SavingScheduleInstallments(account, savingSchedulePeriodData.getDueDate() - .toDate(), savingSchedulePeriodData.getPeriod(), savingSchedulePeriodData.getDepositDue(), - savingSchedulePeriodData.getInterestAccured()); - account.addSavingScheduleInstallment(installment); - } - - return actualChanges; - } - - public void withdrawSavingAccountMoney(final JsonCommand command, final SavingAccount account) { - - LocalDate transactionDate = command.localDateValueOfParameterNamed("transactionDate"); - BigDecimal withdraAmount = command.bigDecimalValueOfParameterNamed("amount"); - if (withdraAmount.doubleValue() > account.getOutstandingAmount().doubleValue()) { throw new DepositAccountTransactionsException( - "deposit.transaction.interest.withdrawal.exceed", "You can Withdraw " + account.getOutstandingAmount() + " only"); } - - account.withdrawAmount(withdraAmount, transactionDate); - - } - - public void postInterest(final SavingAccount account) { - account.postInterest(); - } - - private Boolean isBooleanValueUpdated(final Boolean actualValue) { - Boolean isUpdated = false; - if (actualValue != null) { - isUpdated = true; - } - return isUpdated; - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformService.java deleted file mode 100644 index 475489e7b..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformService.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.math.BigDecimal; -import java.util.Collection; - -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountForLookup; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountTransactionsData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingPermissionData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; - -public interface SavingAccountReadPlatformService { - - Collection retrieveAllSavingsAccounts(); - - SavingAccountData retrieveSavingsAccount(Long accountId); - - SavingAccountData retrieveNewSavingsAccountDetails(Long clientId, Long productId); - - SavingPermissionData retrieveSavingAccountPermissions(SavingAccountData data); - - BigDecimal deriveSavingDueAmount(SavingAccountData account); - - SavingScheduleData retrieveSavingsAccountSchedule(Long accountId, CurrencyData currencyData); - - Collection retrieveSavingAccountsForLookUp(); - - Collection retrieveSavingsAccountTransactions(Long accountId); -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformServiceImpl.java deleted file mode 100644 index 77d926dfb..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountReadPlatformServiceImpl.java +++ /dev/null @@ -1,342 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.List; - -import org.joda.time.LocalDate; -import org.joda.time.Months; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.domain.JdbcSupport; -import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.client.data.ClientData; -import org.mifosplatform.portfolio.client.service.ClientReadPlatformService; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountForLookup; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountTransactionsData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingPermissionData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingSchedulePeriodData; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductData; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductLookup; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductEnumerations; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductReadPlatformService; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountEnumerations; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountTransactionEnumerations; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Service; - -@Service -public class SavingAccountReadPlatformServiceImpl implements SavingAccountReadPlatformService { - - private final PlatformSecurityContext context; - private final JdbcTemplate jdbcTemplate; - private final ClientReadPlatformService clientReadPlatformService; - private final SavingProductReadPlatformService savingProductReadPlatformService; - - @Autowired - public SavingAccountReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource, - final ClientReadPlatformService clientReadPlatformService, - final SavingProductReadPlatformService savingProductReadPlatformService) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.clientReadPlatformService = clientReadPlatformService; - this.savingProductReadPlatformService = savingProductReadPlatformService; - } - - @Override - public Collection retrieveAllSavingsAccounts() { - - this.context.authenticatedUser(); - SavingAccountMapper mapper = new SavingAccountMapper(); - String sql = "select " + mapper.schema() + " where sa.is_deleted=0"; - return this.jdbcTemplate.query(sql, mapper, new Object[] {}); - - } - - @Override - public SavingAccountData retrieveSavingsAccount(final Long accountId) { - - this.context.authenticatedUser(); - SavingAccountMapper mapper = new SavingAccountMapper(); - String sql = "select " + mapper.schema() + " where sa.id = ? and sa.is_deleted=0"; - SavingAccountData savingAccountData = this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { accountId }); - - return savingAccountData; - } - - private static final class SavingAccountMapper implements RowMapper { - - public String schema() { - return "sa.id AS id, sa.status_enum AS status, sa.external_id AS externalId," - + " sa.client_id AS clientId, sa.product_id AS productId, sa.deposit_amount_per_period AS savingsDepostiAmountPerPeriod," - + " sa.savings_product_type AS savingsProductType, sa.currency_code AS currencyCode, sa.currency_digits AS currencyDigits," - + " sa.total_deposit_amount AS totalDepositAmount, sa.reccuring_nominal_interest_rate AS reccuringInterestRate," - + " sa.regular_saving_nominal_interest_rate AS savingInterestRate, sa.tenure AS tenure, sa.tenure_type AS tenureType," - + " sa.frequency AS savingsFrequencyType, sa.interest_type AS interestType, sa.interest_calculation_method AS interestCalculationMethod," - + " sa.projected_commencement_date AS projectedCommencementDate, sa.actual_commencement_date AS actualCommencementDate," - + " sa.matures_on_date AS maturesOnDate, sa.projected_interest_accrued_on_maturity AS projectedInterestAccuredOnMaturity," - + " sa.actual_interest_accrued AS actualInterestAccured, sa.projected_total_maturity_amount AS projectedTotalMaturityAmount," - + " sa.actual_total_amount AS actualTotalAmount, sa.is_preclosure_allowed AS isPreclosureAllowed, sa.outstanding_amount as outstandingAmount, " - + " sa.pre_closure_interest_rate AS preClosureInterestRate, sa.is_lock_in_period_allowed AS isLockinPeriodAllowed," - + " sa.lock_in_period AS lockinPeriod, sa.lock_in_period_type AS lockinPeriodType, sa.withdrawnon_date AS withdrawnonDate," - + " sa.rejectedon_date AS rejectedonDate, sa.closedon_date AS closedonDate, ps.name AS productName, sa.deposit_every as depositEvery, " - + " sa.interest_posting_every AS interestPostEvery, sa.interest_posting_frequency AS interestPostFrequency, " - + " c.firstname AS firstname, c.lastname AS lastname, curr.name AS currencyName, " - + " curr.internationalized_name_code AS currencyNameCode, curr.display_symbol AS currencyDisplaySymbol " - + " FROM m_saving_account sa " + " JOIN m_client c ON c.id = sa.client_id" - + " JOIN m_currency curr ON curr.code = sa.currency_code " + " JOIN m_product_savings ps ON sa.product_id = ps.id "; - } - - @Override - public SavingAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - Long id = rs.getLong("id"); - String externalId = rs.getString("externalId"); - Long clientId = rs.getLong("clientId"); - String clientName = rs.getString("firstname") + " " + rs.getString("lastname"); - - Long productId = rs.getLong("productId"); - String productName = rs.getString("productName"); - EnumOptionData productType = SavingProductEnumerations.savingProductType(JdbcSupport.getInteger(rs, "savingsProductType")); - - Integer statusId = JdbcSupport.getInteger(rs, "status"); - EnumOptionData status = DepositAccountEnumerations.status(statusId); - - String currencyCode = rs.getString("currencyCode"); - String currencyName = rs.getString("currencyName"); - String currencyNameCode = rs.getString("currencyNameCode"); - String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); - Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); - CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, - currencyNameCode); - - BigDecimal savingsDepostiAmountPerPeriod = rs.getBigDecimal("savingsDepostiAmountPerPeriod"); - EnumOptionData savingsFrequencyType = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, - "savingsFrequencyType")); - BigDecimal totalDepositAmount = rs.getBigDecimal("totalDepositAmount"); - - BigDecimal reccuringInterestRate = rs.getBigDecimal("reccuringInterestRate"); - BigDecimal savingInterestRate = rs.getBigDecimal("savingInterestRate"); - EnumOptionData interestType = SavingProductEnumerations.savingInterestType(JdbcSupport.getInteger(rs, "interestType")); - EnumOptionData interestCalculationMethod = SavingProductEnumerations.savingInterestCalculationMethod(JdbcSupport.getInteger(rs, - "interestCalculationMethod")); - - Integer tenure = JdbcSupport.getInteger(rs, "tenure"); - EnumOptionData tenureType = SavingProductEnumerations.tenureTypeEnum(JdbcSupport.getInteger(rs, "tenureType")); - - LocalDate projectedCommencementDate = JdbcSupport.getLocalDate(rs, "projectedCommencementDate"); - LocalDate actualCommencementDate = JdbcSupport.getLocalDate(rs, "actualCommencementDate"); - LocalDate maturesOnDate = JdbcSupport.getLocalDate(rs, "maturesOnDate"); - BigDecimal projectedInterestAccuredOnMaturity = rs.getBigDecimal("projectedInterestAccuredOnMaturity"); - BigDecimal actualInterestAccured = rs.getBigDecimal("actualInterestAccured"); - - BigDecimal projectedMaturityAmount = rs.getBigDecimal("projectedTotalMaturityAmount"); - BigDecimal actualMaturityAmount = rs.getBigDecimal("actualTotalAmount"); - - boolean preClosureAllowed = rs.getBoolean("isPreclosureAllowed"); - BigDecimal preClosureInterestRate = rs.getBigDecimal("preClosureInterestRate"); - BigDecimal outstandingAmount = rs.getBigDecimal("outstandingAmount"); - - LocalDate withdrawnonDate = JdbcSupport.getLocalDate(rs, "withdrawnonDate"); - LocalDate rejectedonDate = JdbcSupport.getLocalDate(rs, "rejectedonDate"); - LocalDate closedonDate = JdbcSupport.getLocalDate(rs, "closedonDate"); - - boolean isLockinPeriodAllowed = rs.getBoolean("isLockinPeriodAllowed"); - Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod"); - Integer lockinPeriodTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodType"); - EnumOptionData lockinPeriodType = SavingProductEnumerations.savingsLockinPeriod(lockinPeriodTypeValue); - Integer depositEvery = JdbcSupport.getInteger(rs, "depositEvery"); - - Integer interestPostEvery = JdbcSupport.getInteger(rs, "interestPostEvery"); - EnumOptionData interestPostFrequency = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, - "interestPostFrequency")); - - return new SavingAccountData(id, status, externalId, clientId, clientName, productId, productName, productType, currencyData, - savingsDepostiAmountPerPeriod, savingsFrequencyType, totalDepositAmount, reccuringInterestRate, savingInterestRate, - interestType, interestCalculationMethod, tenure, tenureType, projectedCommencementDate, actualCommencementDate, - maturesOnDate, projectedInterestAccuredOnMaturity, actualInterestAccured, projectedMaturityAmount, - actualMaturityAmount, preClosureAllowed, preClosureInterestRate, withdrawnonDate, rejectedonDate, closedonDate, - isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, depositEvery, outstandingAmount, interestPostEvery, - interestPostFrequency); - } - } - - @Override - public SavingAccountData retrieveNewSavingsAccountDetails(final Long clientId, final Long productId) { - - context.authenticatedUser(); - ClientData clientAccount = this.clientReadPlatformService.retrieveIndividualClient(clientId); - SavingAccountData accountData = null; - Collection savingProducts = this.savingProductReadPlatformService.retrieveAllSavingProductsForLookup(); - - if (productId != null && productId != -1) { - SavingProductData selectedProduct = findSavingProductById(savingProducts, productId); - - CurrencyData currency = selectedProduct.getCurrency(); - - accountData = new SavingAccountData(clientAccount.id(), clientAccount.displayName(), selectedProduct.getId(), - selectedProduct.getName(), currency, selectedProduct.getInterestRate(), selectedProduct.getSavingsDepositAmount(), - selectedProduct.getSavingProductType(), selectedProduct.getTenureType(), selectedProduct.getTenure(), - selectedProduct.getSavingFrequencyType(), selectedProduct.getInterestType(), - selectedProduct.getInterestCalculationMethod(), selectedProduct.isLockinPeriodAllowed(), - selectedProduct.getLockinPeriod(), selectedProduct.getLockinPeriodType(), selectedProduct.getDepositEvery()); - - } else { - accountData = SavingAccountData.createFrom(clientAccount.id(), clientAccount.displayName()); - } - return accountData; - } - - private SavingProductData findSavingProductById(final Collection savingProducts, final Long productId) { - SavingProductData match = this.savingProductReadPlatformService.retrieveNewSavingProductDetails(); - for (SavingProductLookup savingProductLookup : savingProducts) { - if (savingProductLookup.hasId(productId)) { - match = this.savingProductReadPlatformService.retrieveSavingProduct(savingProductLookup.getId()); - break; - } - } - return match; - } - - @Override - public SavingPermissionData retrieveSavingAccountPermissions(final SavingAccountData savingAccountData) { - boolean pendingApproval = (savingAccountData.getStatus().getId().equals(100L)); - boolean undoApprovalAllowed = (savingAccountData.getStatus().getId().equals(300L)); - boolean renewelAllowed = false; - if (savingAccountData.getMaturesOnDate() != null && savingAccountData.getTenureType().equals(TenureTypeEnum.FIXED_PERIOD)) { - if (new LocalDate().isAfter(savingAccountData.getMaturesOnDate())) { - renewelAllowed = true; - } - } - boolean rejectAllowed = pendingApproval; - boolean withdrawnByApplicantAllowed = pendingApproval; - boolean isMaturedDepositAccount = (savingAccountData.getStatus().getId().equals(700L)); - return new SavingPermissionData(rejectAllowed, withdrawnByApplicantAllowed, undoApprovalAllowed, pendingApproval, renewelAllowed, - isMaturedDepositAccount); - } - - @SuppressWarnings("unused") - @Override - public BigDecimal deriveSavingDueAmount(final SavingAccountData account) { - - BigDecimal dueAmount = BigDecimal.ZERO; - EnumOptionData status = account.getStatus(); - LocalDate date = account.getActualCommencementDate(); - - if (account.getStatus() != null && account.getActualCommencementDate() != null) { - BigDecimal amountPerPeriod = account.getSavingsDepostiAmountPerPeriod(); - Integer tenure = account.getTenure(); - Integer depositEvery = account.getDepositEvery(); - Integer noOfPeriods = tenure / depositEvery; - Integer noOfMonths = Months.monthsBetween(date, new LocalDate()).getMonths(); - Integer noOfPeriodsExistedTillDate = noOfMonths / depositEvery; - BigDecimal totalAmountToBePaidTillDate = BigDecimal.valueOf(noOfPeriodsExistedTillDate.doubleValue() - * amountPerPeriod.doubleValue()); - dueAmount = dueAmount.add(BigDecimal.valueOf(totalAmountToBePaidTillDate.doubleValue() - - account.getOutstandingAmount().doubleValue())); - - } - dueAmount = dueAmount.doubleValue() < 0 ? BigDecimal.ZERO : dueAmount; - return dueAmount; - } - - @Override - public SavingScheduleData retrieveSavingsAccountSchedule(final Long accountId, final CurrencyData currency) { - this.context.authenticatedUser(); - SavingAccountScheduleMapper mapper = new SavingAccountScheduleMapper(); - String sql = "Select " + mapper.savingScheduleSchema() + " where ss.saving_account_id =? order by ss.installment"; - List periods = this.jdbcTemplate.query(sql, mapper, new Object[] { accountId }); - BigDecimal cumulativeDepositDue = BigDecimal.ZERO; - BigDecimal cumulativeDepositPaid = BigDecimal.ZERO; - BigDecimal cummulativeInterestAccured = BigDecimal.ZERO; - for (SavingSchedulePeriodData data : periods) { - cumulativeDepositDue = cumulativeDepositDue.add(data.getDepositDue()); - cumulativeDepositPaid = cumulativeDepositPaid.add(data.getDepositPaid()); - cummulativeInterestAccured = cummulativeInterestAccured.add(data.getInterestAccured()); - } - SavingScheduleData scheduleData = new SavingScheduleData(currency, cumulativeDepositDue, cumulativeDepositPaid, - cummulativeInterestAccured, periods); - return scheduleData; - } - - public static final class SavingAccountScheduleMapper implements RowMapper { - - public String savingScheduleSchema() { - return "ss.id as id, ss.saving_account_id as savingAccountId, ss.duedate as dueDate, ss.installment as installment, " - + " ss.deposit as deposit, ss.payment_date as paymentDate, ss.deposit_paid as depositPaid, " - + " ss.completed_derived as completedDerived, ss.interest_accured AS interestAccured FROM m_saving_schedule ss"; - } - - @Override - public SavingSchedulePeriodData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - LocalDate dueDate = JdbcSupport.getLocalDate(rs, "dueDate"); - Integer installment = JdbcSupport.getInteger(rs, "installment"); - BigDecimal depositDue = rs.getBigDecimal("deposit"); - BigDecimal depositPaid = rs.getBigDecimal("depositPaid"); - BigDecimal interestAccured = rs.getBigDecimal("interestAccured"); - - return new SavingSchedulePeriodData(installment, dueDate, depositDue, depositPaid, interestAccured); - } - - } - - @Override - public Collection retrieveSavingAccountsForLookUp() { - SavingAccountLookupMapper mapper = new SavingAccountLookupMapper(); - String sql = "select " + mapper.schema(); - return this.jdbcTemplate.query(sql, mapper, new Object[] {}); - } - - private static final class SavingAccountLookupMapper implements RowMapper { - - public String schema() { - return " sa.id as id from m_saving_account sa where sa.is_deleted=0 and sa.status_enum=300"; - } - - @Override - public SavingAccountForLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - Long id = rs.getLong("id"); - return new SavingAccountForLookup(id); - } - - } - - @Override - public Collection retrieveSavingsAccountTransactions(final Long accountId) { - this.context.authenticatedUser(); - SavingAccountTransactionMapper savingAccountTransactionMapper = new SavingAccountTransactionMapper(); - String sql = "select " + savingAccountTransactionMapper.schema() + " where stxn.saving_account_id = ? "; - return jdbcTemplate.query(sql, savingAccountTransactionMapper, new Object[] { accountId }); - } - - private static final class SavingAccountTransactionMapper implements RowMapper { - - public String schema() { - return "stxn.id as id, stxn.transaction_type_enum as type, stxn.transaction_date as transactionDate, stxn.amount as amount FROM m_saving_account_transaction stxn"; - } - - @Override - public SavingAccountTransactionsData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - Long id = rs.getLong("id"); - LocalDate transactionDate = JdbcSupport.getLocalDate(rs, "transactionDate"); - Integer transactionTypeValue = JdbcSupport.getInteger(rs, "type"); - EnumOptionData transactionType = DepositAccountTransactionEnumerations.depositType(transactionTypeValue); - BigDecimal amount = rs.getBigDecimal("amount"); - return new SavingAccountTransactionsData(id, transactionDate, transactionType, amount); - } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformService.java deleted file mode 100644 index bfbb4ac8c..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformService.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.util.Collection; - -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountForLookup; - -public interface SavingAccountWritePlatformService { - - CommandProcessingResult createSavingAccount(JsonCommand command); - - CommandProcessingResult updateSavingAccount(Long accountId, JsonCommand command); - - CommandProcessingResult rejectSavingApplication(JsonCommand command); - - CommandProcessingResult withdrawSavingApplication(JsonCommand command); - - CommandProcessingResult undoSavingAccountApproval(JsonCommand undoCommand); - - CommandProcessingResult approveSavingAccount(JsonCommand command); - - CommandProcessingResult depositMoney(JsonCommand command); - - CommandProcessingResult withdrawSavingAmount(JsonCommand command); - - CommandProcessingResult deleteSavingAccount(Long accountId); - - CommandProcessingResult postInterest(Collection savingAccounts); - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformServiceJpaRepositoryImpl.java deleted file mode 100644 index c78563d48..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingAccountWritePlatformServiceJpaRepositoryImpl.java +++ /dev/null @@ -1,327 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.portfolio.note.domain.Note; -import org.mifosplatform.portfolio.note.domain.NoteRepository; -import org.mifosplatform.portfolio.savingsaccount.data.SavingAccountForLookup; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccount; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccountRepository; -import org.mifosplatform.portfolio.savingsaccount.exception.SavingAccountNotFoundException; -import org.mifosplatform.portfolio.savingsaccount.serialization.SavingAccountCommandFromApiJsonDeserializer; -import org.mifosplatform.portfolio.savingsaccount.serialization.SavingAccountStateTransitionCommandFromApiJsonDeserializer; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountStatus; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachine; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachineImpl; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.InvalidSavingStateTransitionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class SavingAccountWritePlatformServiceJpaRepositoryImpl implements SavingAccountWritePlatformService { - - private final static Logger logger = LoggerFactory.getLogger(SavingAccountWritePlatformServiceJpaRepositoryImpl.class); - - private final PlatformSecurityContext context; - private final SavingAccountRepository savingAccountRepository; - private final SavingAccountAssembler savingAccountAssembler; - private final NoteRepository noteRepository; - private final SavingAccountCommandFromApiJsonDeserializer fromApiJsonDeserializer; - private final SavingAccountStateTransitionCommandFromApiJsonDeserializer savingAccountStateTransitionCommandFromApiJsonDeserializer; - - @Autowired - public SavingAccountWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final SavingAccountRepository savingAccountRepository, final SavingAccountAssembler savingAccountAssembler, - final NoteRepository noteRepository, - final SavingAccountCommandFromApiJsonDeserializer fromApiJsonDeserializer, - final SavingAccountStateTransitionCommandFromApiJsonDeserializer savingAccountStateTransitionCommandFromApiJsonDeserializer) { - this.context = context; - this.savingAccountRepository = savingAccountRepository; - this.savingAccountAssembler = savingAccountAssembler; - this.noteRepository = noteRepository; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; - this.savingAccountStateTransitionCommandFromApiJsonDeserializer = savingAccountStateTransitionCommandFromApiJsonDeserializer; - } - - @Transactional - @Override - public CommandProcessingResult createSavingAccount(final JsonCommand command) { - try { - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForCreate(command.json()); - - SavingAccount account = this.savingAccountAssembler.assembleFrom(command); - this.savingAccountRepository.save(account); - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return new CommandProcessingResult(Long.valueOf(-1)); - } - - } - - @Override - public CommandProcessingResult updateSavingAccount(final Long accountId, final JsonCommand command) { - try { - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForUpdate(command.json()); - - Map changes = new LinkedHashMap(20);; - - SavingAccount account = this.savingAccountRepository.findOne(accountId); - if (account == null || account.isDeleted()) { throw new SavingAccountNotFoundException(accountId); } - if (account.isPendingApproval()) { - changes = this.savingAccountAssembler.assembleFrom(command, account); - this.savingAccountRepository.save(account); - } - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .with(changes) - .build(); - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return new CommandProcessingResult(Long.valueOf(-1)); - } - } - - /* - * Guaranteed to throw an exception no matter what the data integrity issue - * is. - */ - private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - - Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("saving_acc_external_id")) { - final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException( - "error.msg.saving.account.duplicate.externalId", "Saving account with externalId " + externalId - + " already exists", "externalId", externalId); } - - logger.error(dve.getMessage(), dve); - throw new PlatformDataIntegrityException("error.msg.saving.account.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } - - @Override - public CommandProcessingResult rejectSavingApplication(JsonCommand command) { - - this.context.authenticatedUser(); - this.savingAccountStateTransitionCommandFromApiJsonDeserializer.validateForReject(command.json()); - - SavingAccount account = this.savingAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(command.entityId()); - } - LocalDate eventDate = command.localDateValueOfParameterNamed("eventDate"); - if (this.isBeforeToday(eventDate)) { - final String errorMessage = "User has no authority to reject saving with a date in the past. "; - - throw new InvalidSavingStateTransitionException("reject", "cannot.be.before.submittal.date", errorMessage, account.projectedCommencementDate(), eventDate); - } - account.reject(eventDate, defaultDepositLifecycleStateMachine()); - this.savingAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.savingNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() { - List allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values()); - return new DepositLifecycleStateMachineImpl(allowedDepositStatuses); - } - - @Override - public CommandProcessingResult withdrawSavingApplication(JsonCommand command) { - this.context.authenticatedUser(); - this.savingAccountStateTransitionCommandFromApiJsonDeserializer.validateForWithdrawApplication(command.json()); - - SavingAccount account = this.savingAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(command.entityId()); - } - LocalDate eventDate = command.localDateValueOfParameterNamed("eventDate"); - if (this.isBeforeToday(eventDate)) { - final String errorMessage = "User has no authority to withdraw saving with a date in the past. "; - - throw new InvalidSavingStateTransitionException("reject", "cannot.be.before.submittal.date", errorMessage, account.projectedCommencementDate(), eventDate); - } - - account.withdrawnByApplicant(eventDate, defaultDepositLifecycleStateMachine()); - this.savingAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.savingNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Override - public CommandProcessingResult undoSavingAccountApproval(JsonCommand command) { - - this.context.authenticatedUser(); - SavingAccount account = this.savingAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(command.getLoanId()); - } - account.undoSavingAccountApproval(defaultDepositLifecycleStateMachine()); - this.savingAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.savingNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Override - public CommandProcessingResult approveSavingAccount(JsonCommand command) { - - this.context.authenticatedUser(); - this.savingAccountStateTransitionCommandFromApiJsonDeserializer.validateForApprove(command.json()); - - SavingAccount account = this.savingAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(command.entityId()); - } - LocalDate approvalDate = command.localDateValueOfParameterNamed("commencementDate"); - if (approvalDate.isBefore(account.projectedCommencementDate())) { - final String errorMessage = "The date on which a saving is approved cannot be before its submittal date: " - + approvalDate.toString(); - - throw new InvalidSavingStateTransitionException("approval", "cannot.be.before.submittal.date", errorMessage, - account.projectedCommencementDate(), approvalDate); - } - Map changes = this.savingAccountAssembler.approveSavingAccount(command,account); - this.savingAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.savingNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .with(changes) - .build(); - } - - @Override - public CommandProcessingResult depositMoney(JsonCommand command) { - - this.context.authenticatedUser(); - this.savingAccountStateTransitionCommandFromApiJsonDeserializer.validateForDepositAmount(command.json()); - - SavingAccount account = this.savingAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(command.entityId()); - } - - if (account.isActive()) - account.depositMoney(command); - this.savingAccountRepository.save(account); - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.savingNote(account, noteText); - this.noteRepository.save(note); - } - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Override - public CommandProcessingResult withdrawSavingAmount(JsonCommand command) { - - this.context.authenticatedUser(); - SavingAccount account = this.savingAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(command.entityId()); - } - if (account.isActive()) - this.savingAccountAssembler.withdrawSavingAccountMoney(command,account); - this.savingAccountRepository.save(account); - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.savingNote(account, noteText); - this.noteRepository.save(note); - } - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Override - public CommandProcessingResult deleteSavingAccount(Long accountId) { - this.context.authenticatedUser(); - SavingAccount account = this.savingAccountRepository.findOne(accountId); - if (account == null || account.isDeleted()) { - throw new SavingAccountNotFoundException(accountId); - } - account.delete(); - this.savingAccountRepository.save(account); - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Override - public CommandProcessingResult postInterest(Collection savingAccounts) { - this.context.authenticatedUser(); - try { - for(SavingAccountForLookup accountForLookup : savingAccounts ){ - SavingAccount account = this.savingAccountRepository.findOne(accountForLookup.getId()); - if (account == null || account.isDeleted()) { throw new SavingAccountNotFoundException(accountForLookup.getId()); } - this.savingAccountAssembler.postInterest(account); - this.savingAccountRepository.save(account); - } - return new CommandProcessingResultBuilder() // - .withEntityId(Long.valueOf(savingAccounts.size())) // - .build(); - } catch (Exception e) { - return new CommandProcessingResult(Long.valueOf(-1)); - } - } - private boolean isBeforeToday(final LocalDate date) { - return date.isBefore(new LocalDate()); - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleAssembler.java deleted file mode 100644 index a23d9eedf..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleAssembler.java +++ /dev/null @@ -1,139 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Collection; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.organisation.monetary.domain.ApplicationCurrency; -import org.mifosplatform.organisation.monetary.domain.ApplicationCurrencyRepository; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingSchedulePeriodData; -import org.mifosplatform.portfolio.savingsaccount.domain.SavingAccount; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductRepository; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.exception.SavingProductNotFoundException; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.google.gson.JsonElement; - -@Service -public class SavingScheduleAssembler { - - private final FromJsonHelper fromApiJsonHelper; - private final SavingProductRepository savingProductRepository; - private final SavingScheduleGenerator savingScheduleGenerator; - private final ApplicationCurrencyRepository applicationCurrencyRepository; - - @Autowired - public SavingScheduleAssembler( final FromJsonHelper fromApiJsonHelper, - final SavingProductRepository savingProductRepository, - final ApplicationCurrencyRepository applicationCurrencyRepository) { - this.fromApiJsonHelper = fromApiJsonHelper; - this.savingProductRepository = savingProductRepository; - this.savingScheduleGenerator = new SavingScheduleGenerator(); - this.applicationCurrencyRepository = applicationCurrencyRepository; - } - - public SavingScheduleData fromJson(JsonElement element) { - - SavingScheduleData savingScheduleData = null; - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - final Integer depositEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed("depositEvery", element); - final LocalDate scheduleStartDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - final BigDecimal interestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("recurringInterestRate", element); - final BigDecimal depositAmountPerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingsDepositAmountPerPeriod", element); - final Integer tenure = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("tenure", element); - - final Integer tenureTypeCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("tenureType", element); - TenureTypeEnum tenureType = TenureTypeEnum.fromInt(tenureTypeCommandValue); - final Integer frequencyCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("frequency", element); - SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(frequencyCommandValue); - //final Integer interestTypeCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("interestType", element); - //SavingsInterestType interestType = SavingsInterestType.fromInt(interestTypeCommandValue); - final Integer interestCalculationMethodCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("interestCalculationMethod", element); - SavingInterestCalculationMethod interestCalculationMethod = SavingInterestCalculationMethod.fromInt(interestCalculationMethodCommandValue); - - final SavingProduct savingProduct = this.savingProductRepository.findOne(productId); - if (savingProduct == null) throw new SavingProductNotFoundException(productId); - final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneByCode(savingProduct.getCurrency().getCode()); - - SavingProductType savingProductType = SavingProductType.fromInt(savingProduct.getSavingProductRelatedDetail().getSavingProductType()); - - if (savingProductType.isReccuring() && tenureType.isFixedPeriod()) { - savingScheduleData = savingScheduleGenerator.generate(scheduleStartDate, depositAmountPerPeriod, - depositEvery, savingFrequencyType, savingProduct, tenure, applicationCurrency,interestRate,interestCalculationMethod); - } else { - final Collection periods = new ArrayList(); - CurrencyData currencyData = new CurrencyData(applicationCurrency.getCode(), applicationCurrency.getName(), - savingProduct.getCurrency().getDigitsAfterDecimal(), applicationCurrency.getDisplaySymbol(), applicationCurrency.getNameCode()); - SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(1, new LocalDate(scheduleStartDate).plusMonths(depositEvery), depositAmountPerPeriod, BigDecimal.ZERO); - periods.add(installment); - savingScheduleData = new SavingScheduleData(currencyData, depositAmountPerPeriod, BigDecimal.ZERO, BigDecimal.ZERO, periods); - } - - return savingScheduleData; - } - - public SavingScheduleData calculateSavingSchedule(JsonElement element, SavingAccount account) { - - SavingScheduleData savingScheduleData = null; - - SavingProduct savingProduct = account.getProduct(); - SavingProductType savingProductType = SavingProductType.fromInt(account.getSavingProductType()); - SavingInterestCalculationMethod interestCalculationMethod = SavingInterestCalculationMethod.fromInt(account.getInterestCalculationMethod()); - - TenureTypeEnum tenureType = TenureTypeEnum.fromInt(account.getTenureType()); - final Integer tenureTypeCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("tenureType", element); - if (tenureTypeCommandValue != null) tenureType = TenureTypeEnum.fromInt(tenureTypeCommandValue); - - LocalDate scheduleStartDate = new LocalDate(account.getProjectedCommencementDate()); - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - if (commencementDate != null) scheduleStartDate = commencementDate ; - - BigDecimal depositAmountPerPeriod = account.getSavingsDepositAmountPerPeriod(); - final BigDecimal savingsDepositAmountPerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingsDepositAmountPerPeriod", element); - if (savingsDepositAmountPerPeriod != null ) depositAmountPerPeriod = savingsDepositAmountPerPeriod; - - Integer depositEvery = account.getPayEvery(); - final Integer depositEveryCommandValue = fromApiJsonHelper.extractIntegerWithLocaleNamed("depositEvery", element); - if (depositEveryCommandValue != null ) depositEvery = depositEveryCommandValue; - - SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(account.getFrequency()); - final Integer frequencyCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("frequency", element); - if (frequencyCommandValue != null ) savingFrequencyType = SavingFrequencyType.fromInt(frequencyCommandValue); - - Integer tenure = account.getTenure(); - final Integer tenureCommandValue = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("tenure", element); - if (tenureCommandValue != null ) tenure = tenureCommandValue; - - BigDecimal interestRate = account.getReccuringInterestRate(); - final BigDecimal recurringInterestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("recurringInterestRate", element); - if (recurringInterestRate != null ) interestRate = recurringInterestRate; - - final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneByCode(savingProduct.getCurrency().getCode()); - - if (savingProductType.isReccuring() && tenureType.isFixedPeriod()) { - savingScheduleData = savingScheduleGenerator.generate(scheduleStartDate, depositAmountPerPeriod, - depositEvery, savingFrequencyType, savingProduct, tenure, applicationCurrency,interestRate,interestCalculationMethod); - } else { - final Collection periods = new ArrayList(); - CurrencyData currencyData = new CurrencyData(applicationCurrency.getCode(), applicationCurrency.getName(), - savingProduct.getCurrency().getDigitsAfterDecimal(), applicationCurrency.getDisplaySymbol(), applicationCurrency.getNameCode()); - SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(1, new LocalDate(scheduleStartDate).plusMonths(depositEvery), depositAmountPerPeriod, BigDecimal.ZERO); - periods.add(installment); - savingScheduleData = new SavingScheduleData(currencyData, depositAmountPerPeriod, BigDecimal.ZERO, BigDecimal.ZERO, periods); - } - - return savingScheduleData; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleGenerator.java deleted file mode 100644 index 58e15dba7..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccount/service/SavingScheduleGenerator.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccount.service; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.joda.time.LocalDate; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.organisation.monetary.domain.ApplicationCurrency; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.savingsaccount.data.SavingScheduleData; -import org.mifosplatform.portfolio.savingsaccount.data.SavingSchedulePeriodData; -import org.mifosplatform.portfolio.savingsaccount.domain.DepositScheduleDateGenerator; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct; - -public class SavingScheduleGenerator { - - private final DepositScheduleDateGenerator scheduledDateGenerator = new DefaultDepositScheduleDateGenerator(); - private final Integer monthsInYear = 12; - - public SavingScheduleData generate(final LocalDate scheduleStartDate, final BigDecimal depositAmountPerPeriod, - final Integer depositFrequency, final SavingFrequencyType savingFrequencyType, final SavingProduct savingProduct, - final Integer tenure, final ApplicationCurrency applicationCurrency, final BigDecimal interestRate, final SavingInterestCalculationMethod interestCalculationMethod) { - - LocalDate startDate = scheduleStartDate; - int periodNumber = 1; - - Integer paymentPeriods = tenure / depositFrequency; - final Collection periods = new ArrayList(); - final List scheduledDates = this.scheduledDateGenerator.generate(startDate, paymentPeriods, depositFrequency, - savingFrequencyType); - final MonetaryCurrency currency = savingProduct.getCurrency(); - final Money depositAmount = Money.of(currency, depositAmountPerPeriod); - Money totalDeposit = Money.zero(currency); - - - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - BigDecimal interestRateAsFraction = interestRate.divide(BigDecimal.valueOf(100), mc); - Integer noofTimesInterestCompoundPerYear = determineIntValue(savingFrequencyType); - BigDecimal interestRatePerPeriod = BigDecimal.valueOf(interestRateAsFraction.doubleValue()/ noofTimesInterestCompoundPerYear.doubleValue()); - BigDecimal onePlusInterestRatePerPeriod = BigDecimal.ONE.add(interestRatePerPeriod); - BigDecimal cummulativeDepositPaid = BigDecimal.ZERO; - BigDecimal cummulativeInterestAccured = BigDecimal.ZERO; - Integer tempTenure = tenure; - - BigDecimal termAmount = BigDecimal.ZERO; - BigDecimal totalInterest = BigDecimal.ZERO; - BigDecimal closingBalance = BigDecimal.ZERO; - - for (LocalDate scheduleDate : scheduledDates) { - - if (interestCalculationMethod.isMonthlyCollection()) { - BigDecimal monthsExpressedInYears = BigDecimal.valueOf(tempTenure.doubleValue() / monthsInYear.doubleValue()); - BigDecimal timeforOneCalculationPeriod = BigDecimal.valueOf(noofTimesInterestCompoundPerYear * monthsExpressedInYears.doubleValue()); - BigDecimal amountPerPeriod = depositAmountPerPeriod.multiply(BigDecimal.valueOf(Math.pow(onePlusInterestRatePerPeriod.doubleValue(), timeforOneCalculationPeriod.doubleValue()))); - BigDecimal interestAccured = amountPerPeriod.subtract(depositAmountPerPeriod); - - totalDeposit = totalDeposit.plus(depositAmount); - cummulativeInterestAccured = cummulativeInterestAccured.add(interestAccured); - SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(periodNumber, scheduleDate, - depositAmount.getAmount(), interestAccured); - periods.add(installment); - periodNumber++; - tempTenure = tempTenure - depositFrequency; - } else if (interestCalculationMethod.isAverageBalance()){ - - BigDecimal amountPerPeriod = depositAmount.getAmount(); - Integer depositEveryOriginalValue = depositFrequency; - BigDecimal amountPermonth = BigDecimal.valueOf(amountPerPeriod.doubleValue()/depositFrequency.doubleValue()); - - while (depositEveryOriginalValue > 0) { - closingBalance = closingBalance.add(amountPermonth); - termAmount = termAmount.add(closingBalance); - depositEveryOriginalValue--; - } - - BigDecimal averageAmount = BigDecimal.valueOf(termAmount.doubleValue()/depositFrequency.doubleValue()); - BigDecimal interestRatePerTerm = BigDecimal.valueOf(interestRateAsFraction.doubleValue()/monthsInYear.doubleValue()*depositFrequency.doubleValue()); - BigDecimal interestAccured = averageAmount.multiply(interestRatePerTerm); - totalInterest = totalInterest.add(interestAccured); - depositEveryOriginalValue = depositFrequency; - termAmount = BigDecimal.ZERO; - - totalDeposit = totalDeposit.plus(depositAmount); - cummulativeInterestAccured = totalInterest; - SavingSchedulePeriodData installment = SavingSchedulePeriodData.addScheduleInformation(periodNumber, scheduleDate, - depositAmount.getAmount(), interestAccured); - periods.add(installment); - periodNumber++; - } - } - CurrencyData currencyData = new CurrencyData(applicationCurrency.getCode(), applicationCurrency.getName(), - currency.getDigitsAfterDecimal(), applicationCurrency.getDisplaySymbol(), applicationCurrency.getNameCode()); - - return new SavingScheduleData(currencyData, totalDeposit.getAmount(),cummulativeDepositPaid, cummulativeInterestAccured, periods); - } - - private Integer determineIntValue(SavingFrequencyType frequencyType){ - Integer noofTimesInterestCompoundPerYear = Integer.valueOf(0); - switch (frequencyType) { - case MONTHLY: - noofTimesInterestCompoundPerYear = monthsInYear; - break; - case QUATERLY: - noofTimesInterestCompoundPerYear = monthsInYear / 3; - break; - case HALFYEARLY: - noofTimesInterestCompoundPerYear = monthsInYear / 6; - break; - case YEARLY: - noofTimesInterestCompoundPerYear = monthsInYear / 12; - break; - default: - throw new RuntimeException("The specified frequency not supported"); - - } - return noofTimesInterestCompoundPerYear; - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/api/SavingProductsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/api/SavingProductsApiResource.java deleted file mode 100644 index 41029b5e2..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/api/SavingProductsApiResource.java +++ /dev/null @@ -1,207 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.api; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriInfo; - -import org.mifosplatform.commands.domain.CommandWrapper; -import org.mifosplatform.commands.service.CommandWrapperBuilder; -import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; -import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; -import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.organisation.monetary.service.CurrencyReadPlatformService; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductData; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsLockinPeriodEnum; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductEnumerations; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductReadPlatformService; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -@Path("/savingproducts") -@Component -@Scope("singleton") -public class SavingProductsApiResource { - - private final Set SAVINGS_PRODUCT_DATA_PARAMETERS = new HashSet(Arrays.asList("currencyOptions", "id", "createdOn", - "lastModifedOn", "locale", "name", "description", "currencyCode", "digitsAfterDecimal", "interstRate", "minInterestRate", - "maxInterestRate", "savingsDepositAmount", "savingProductType", "tenureType", "tenure", "frequency", "interestType", - "interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "isLockinPeriodAllowed", "lockinPeriod", - "lockinPeriodType", "currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions", "depositEvery", - "savingFrequencyOptions", "savingsInterestTypeOptions", "lockinPeriodTypeOptions", "interestCalculationOptions")); - - private final SavingProductReadPlatformService savingProductReadPlatformService; - private final CurrencyReadPlatformService currencyReadPlatformService; - private final String entityType = "SAVINGSPRODUCT"; - private final PlatformSecurityContext context; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private final ApiRequestParameterHelper apiRequestParameterHelper; - - @Autowired - public SavingProductsApiResource(final SavingProductReadPlatformService savingProductReadPlatformService, - final CurrencyReadPlatformService currencyReadPlatformService, final PlatformSecurityContext context, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper) { - this.savingProductReadPlatformService = savingProductReadPlatformService; - this.currencyReadPlatformService = currencyReadPlatformService; - this.context = context; - this.toApiJsonSerializer = toApiJsonSerializer; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.apiRequestParameterHelper = apiRequestParameterHelper; - } - - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String createSavingProduct(final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingProduct().withJson(apiRequestBodyAsJson).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - - } - - @PUT - @Path("{productId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateSavingProduct(@PathParam("productId") final Long productId, final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSavingProduct(productId).withJson(apiRequestBodyAsJson) - .build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - - } - - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAllSavingProducts(@Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - Collection products = this.savingProductReadPlatformService.retrieveAllSavingProducts(); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - return this.toApiJsonSerializer.serialize(settings, products, SAVINGS_PRODUCT_DATA_PARAMETERS); - } - - @GET - @Path("{productId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveSavingProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveSavingProduct(productId); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - if (settings.isTemplate()) { - savingProduct = handleTemplateRelatedData(savingProduct); - } - - return this.toApiJsonSerializer.serialize(settings, savingProduct, SAVINGS_PRODUCT_DATA_PARAMETERS); - } - - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveNewSavingProductDetails(@Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - SavingProductData savingProduct = this.savingProductReadPlatformService.retrieveNewSavingProductDetails(); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - savingProduct = handleTemplateRelatedData(savingProduct); - - return this.toApiJsonSerializer.serialize(settings, savingProduct, SAVINGS_PRODUCT_DATA_PARAMETERS); - } - - private SavingProductData handleTemplateRelatedData(final SavingProductData savingProduct) { - - Collection currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); - - EnumOptionData reccuring = SavingProductEnumerations.savingProductType(SavingProductType.RECURRING); - EnumOptionData regular = SavingProductEnumerations.savingProductType(SavingProductType.REGULAR); - List savingsProductTypeOptions = Arrays.asList(reccuring, regular); - - EnumOptionData fixed = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD); - EnumOptionData perpetual = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.PERPETUAL); - List tenureTypeOptions = Arrays.asList(fixed, perpetual); - - EnumOptionData monthly = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY); - List savingFrequencyOptions = Arrays.asList(monthly); - - EnumOptionData simple = SavingProductEnumerations.savingInterestType(SavingsInterestType.SIMPLE); - EnumOptionData compounding = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING); - List savingsInterestTypeOptions = Arrays.asList(simple, compounding); - - EnumOptionData months = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS); - List lockinPeriodTypeOptions = Arrays.asList(months); - - EnumOptionData averagebal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL); - EnumOptionData minbal = SavingProductEnumerations.savingInterestCalculationMethod(SavingInterestCalculationMethod.MINBAL); - EnumOptionData monthlyCollection = SavingProductEnumerations - .savingInterestCalculationMethod(SavingInterestCalculationMethod.MONTHLYCOLLECTION); - List interestCalculationOptions = Arrays.asList(averagebal, minbal, monthlyCollection); - - return new SavingProductData(savingProduct, currencyOptions, savingsProductTypeOptions, tenureTypeOptions, savingFrequencyOptions, - savingsInterestTypeOptions, lockinPeriodTypeOptions, interestCalculationOptions); - } - - @DELETE - @Path("{productId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String deleteProduct(@PathParam("productId") final Long productId) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingProduct(productId).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductData.java deleted file mode 100644 index 13ede5036..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductData.java +++ /dev/null @@ -1,279 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.data; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.joda.time.DateTime; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsLockinPeriodEnum; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductEnumerations; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; - -public class SavingProductData implements Serializable { - - private final Long id; - private final String name; - private final String description; - private final CurrencyData currency; - private final Integer digitsAfterDecimal; - - private final BigDecimal interestRate; - private final BigDecimal minInterestRate; - private final BigDecimal maxInterestRate; - private final BigDecimal savingsDepositAmount; - private final EnumOptionData savingProductType; - private final EnumOptionData tenureType; - private final Integer tenure; - private final EnumOptionData savingFrequencyType; - private final EnumOptionData interestType; - private final EnumOptionData interestCalculationMethod; - private final BigDecimal minimumBalanceForWithdrawal; - private final boolean isPartialDepositAllowed; - private final boolean isLockinPeriodAllowed; - private final Integer lockinPeriod; - private final EnumOptionData lockinPeriodType; - - private DateTime createdOn; - private DateTime lastModifedOn; - private final Integer depositEvery; - - @SuppressWarnings("unused") - private Collection currencyOptions = new ArrayList(); - private List savingsProductTypeOptions = new ArrayList(); - private List tenureTypeOptions = new ArrayList(); - private List savingFrequencyOptions = new ArrayList(); - private List savingsInterestTypeOptions = new ArrayList(); - private List lockinPeriodTypeOptions = new ArrayList(); - private List interestCalculationOptions = new ArrayList(); - - public SavingProductData() { - this.createdOn = new DateTime(); - this.lastModifedOn = new DateTime(); - this.id = null; - this.name = null; - this.description = null; - this.interestRate = BigDecimal.ZERO; - this.minInterestRate = BigDecimal.ZERO; - this.maxInterestRate = BigDecimal.ZERO; - this.currency = new CurrencyData("USD", "US Dollar", 2, "$", "currency.USD"); - this.digitsAfterDecimal = Integer.valueOf(2); - this.savingsDepositAmount = BigDecimal.ZERO; - this.savingProductType = SavingProductEnumerations.savingProductType(SavingProductType.RECURRING); - this.tenureType = SavingProductEnumerations.tenureTypeEnum(TenureTypeEnum.FIXED_PERIOD); - this.tenure = Integer.valueOf(12); - this.savingFrequencyType = SavingProductEnumerations.interestFrequencyType(SavingFrequencyType.MONTHLY); - this.interestType = SavingProductEnumerations.savingInterestType(SavingsInterestType.COMPOUNDING); - this.interestCalculationMethod = SavingProductEnumerations - .savingInterestCalculationMethod(SavingInterestCalculationMethod.AVERAGEBAL); - this.minimumBalanceForWithdrawal = BigDecimal.valueOf(100); - this.isPartialDepositAllowed = false; - this.isLockinPeriodAllowed = false; - this.lockinPeriod = Integer.valueOf(0); - this.lockinPeriodType = SavingProductEnumerations.savingsLockinPeriod(SavingsLockinPeriodEnum.MONTHS); - this.depositEvery = Integer.valueOf(3); - } - - public SavingProductData(DateTime createdOn, DateTime lastModifedOn, Long id, String name, String description, BigDecimal interestRate, - BigDecimal minInterestRate, BigDecimal maxInterestRate, CurrencyData currency, Integer digitsAfterDecimal, - BigDecimal savingsDepositAmount, EnumOptionData savingProductType, EnumOptionData tenureType, Integer tenure, - EnumOptionData savingFrequencyType, EnumOptionData savingInterestType, EnumOptionData interestCalculationMethod, - BigDecimal minimumBalanceForWithdrawal, boolean isPartialDepositAllowed, boolean isLockinPeriodAllowed, Integer lockinPeriod, - EnumOptionData lockinPeriodType, Integer depositEvery) { - this.createdOn = createdOn; - this.lastModifedOn = lastModifedOn; - this.id = id; - this.name = name; - this.description = description; - this.interestRate = interestRate; - this.minInterestRate = minInterestRate; - this.maxInterestRate = maxInterestRate; - this.currency = currency; - this.digitsAfterDecimal = digitsAfterDecimal; - this.savingsDepositAmount = savingsDepositAmount; - this.savingProductType = savingProductType; - this.tenureType = tenureType; - this.tenure = tenure; - this.savingFrequencyType = savingFrequencyType; - this.interestType = savingInterestType; - this.interestCalculationMethod = interestCalculationMethod; - this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal; - this.isPartialDepositAllowed = isPartialDepositAllowed; - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - this.depositEvery = depositEvery; - } - - public SavingProductData(SavingProductData product, Collection currencyOptions, - List savingsProductTypeOptions, List tenureTypeOptions, - List savingFrequencyOptions, List savingsInterestTypeOptions, - List lockinPeriodTypeOptions, List interestCalculationOptions) { - - this.createdOn = product.getCreatedOn(); - this.lastModifedOn = product.getLastModifedOn(); - this.id = product.getId(); - this.name = product.getName(); - this.description = product.getDescription(); - this.interestRate = product.getInterestRate(); - this.minInterestRate = product.getMinInterestRate(); - this.maxInterestRate = product.getMaxInterestRate(); - this.currency = product.getCurrency(); - this.digitsAfterDecimal = product.getDigitsAfterDecimal(); - this.savingsDepositAmount = product.getSavingsDepositAmount(); - this.savingProductType = product.getSavingProductType(); - this.tenureType = product.getTenureType(); - this.tenure = product.getTenure(); - this.savingFrequencyType = product.getSavingFrequencyType(); - this.interestType = product.getInterestType(); - this.interestCalculationMethod = product.getInterestCalculationMethod(); - this.minimumBalanceForWithdrawal = product.getMinimumBalanceForWithdrawal(); - this.isPartialDepositAllowed = product.isPartialDepositAllowed(); - this.isLockinPeriodAllowed = product.isLockinPeriodAllowed(); - this.lockinPeriod = product.getLockinPeriod(); - this.lockinPeriodType = product.getLockinPeriodType(); - this.depositEvery = product.getDepositEvery(); - - this.currencyOptions = currencyOptions; - this.savingsProductTypeOptions = savingsProductTypeOptions; - this.tenureTypeOptions = tenureTypeOptions; - this.savingFrequencyOptions = savingFrequencyOptions; - this.savingsInterestTypeOptions = savingsInterestTypeOptions; - this.lockinPeriodTypeOptions = lockinPeriodTypeOptions; - this.interestCalculationOptions = interestCalculationOptions; - - } - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public CurrencyData getCurrency() { - return currency; - } - - public Integer getDigitsAfterDecimal() { - return digitsAfterDecimal; - } - - public BigDecimal getInterestRate() { - return interestRate; - } - - public BigDecimal getMinInterestRate() { - return minInterestRate; - } - - public BigDecimal getMaxInterestRate() { - return maxInterestRate; - } - - public BigDecimal getSavingsDepositAmount() { - return savingsDepositAmount; - } - - public EnumOptionData getSavingProductType() { - return savingProductType; - } - - public EnumOptionData getTenureType() { - return tenureType; - } - - public Integer getTenure() { - return tenure; - } - - public EnumOptionData getInterestType() { - return interestType; - } - - public EnumOptionData getInterestCalculationMethod() { - return interestCalculationMethod; - } - - public BigDecimal getMinimumBalanceForWithdrawal() { - return minimumBalanceForWithdrawal; - } - - public boolean isPartialDepositAllowed() { - return isPartialDepositAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public EnumOptionData getLockinPeriodType() { - return lockinPeriodType; - } - - public DateTime getCreatedOn() { - return createdOn; - } - - public DateTime getLastModifedOn() { - return lastModifedOn; - } - - public void setCurrencyOptions(Collection currencyOptions) { - this.currencyOptions = currencyOptions; - } - - public EnumOptionData getSavingFrequencyType() { - return savingFrequencyType; - } - - public List getSavingsProductTypeOptions() { - return savingsProductTypeOptions; - } - - public List getTenureTypeOptions() { - return tenureTypeOptions; - } - - public List getSavingFrequencyOptions() { - return savingFrequencyOptions; - } - - public List getSavingsInterestTypeOptions() { - return savingsInterestTypeOptions; - } - - public List getLockinPeriodTypeOptions() { - return lockinPeriodTypeOptions; - } - - public List getInterestCalculationOptions() { - return interestCalculationOptions; - } - - public Integer getDepositEvery() { - return this.depositEvery; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductLookup.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductLookup.java deleted file mode 100644 index da667f8c7..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/data/SavingProductLookup.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.data; - -import java.io.Serializable; - -public class SavingProductLookup implements Serializable { - - private final Long id; - private final String name; - - public SavingProductLookup() { - this.id = null; - this.name = null; - } - - public SavingProductLookup(final Long id, final String name) { - this.id = id; - this.name = name; - } - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - - public boolean hasId(final Long matchingId) { - return this.id.equals(matchingId); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingFrequencyType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingFrequencyType.java deleted file mode 100644 index 88c92fa77..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingFrequencyType.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -public enum SavingFrequencyType { - - INVALID(0, "savingFrequencyType.invalid"), // - DAILY(1, "savingFrequencyType.daily"), // - MONTHLY(2, "savingFrequencyType.monthly"), // - QUATERLY(3, "savingFrequencyType.quaterly"), // - HALFYEARLY(4, "savingFrequencyType.halfyearly"), // - YEARLY(5, "savingFrequencyType.yearly"); - - private final Integer value; - private final String code; - - private SavingFrequencyType(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public static SavingFrequencyType fromInt(final Integer frequency) { - - SavingFrequencyType savingFrequencyType = SavingFrequencyType.INVALID; - switch (frequency) { - case 1: - savingFrequencyType = SavingFrequencyType.DAILY; - break; - case 2: - savingFrequencyType = SavingFrequencyType.MONTHLY; - break; - case 3: - savingFrequencyType = SavingFrequencyType.QUATERLY; - break; - case 4: - savingFrequencyType = SavingFrequencyType.HALFYEARLY; - break; - case 5: - savingFrequencyType = SavingFrequencyType.YEARLY; - break; - default: - savingFrequencyType = SavingFrequencyType.INVALID; - break; - } - return savingFrequencyType; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingInterestCalculationMethod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingInterestCalculationMethod.java deleted file mode 100644 index f0747a96a..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingInterestCalculationMethod.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -public enum SavingInterestCalculationMethod { - - INVALID(0, "savinginterest.calculation.method.invalid"), // - AVERAGEBAL(1, "savinginterest.calculation.method.averagebal"), // - MINBAL(2, "savinginterest.calculation.method.minbal"), // - MONTHLYCOLLECTION(3, "savinginterest.calculation.method.monthlycllection"); - - private final Integer value; - private final String code; - - private SavingInterestCalculationMethod(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public static SavingInterestCalculationMethod fromInt(final Integer frequency) { - - SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID; - switch (frequency) { - case 1: - savingInterestCalculationMethod = SavingInterestCalculationMethod.AVERAGEBAL; - break; - case 2: - savingInterestCalculationMethod = SavingInterestCalculationMethod.MINBAL; - break; - case 3: - savingInterestCalculationMethod = SavingInterestCalculationMethod.MONTHLYCOLLECTION; - break; - default: - savingInterestCalculationMethod = SavingInterestCalculationMethod.INVALID; - break; - } - return savingInterestCalculationMethod; - } - - public boolean isAverageBalance() { - return this.value.equals(SavingInterestCalculationMethod.AVERAGEBAL.value); - } - - public boolean isMonthlyCollection() { - return this.value.equals(SavingInterestCalculationMethod.MONTHLYCOLLECTION.value); - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProduct.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProduct.java deleted file mode 100644 index 5397bee6c..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProduct.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -import java.math.BigDecimal; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.Table; - -import org.apache.commons.lang.StringUtils; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.mifosplatform.useradministration.domain.AppUser; - -@Entity -@Table(name = "m_product_savings") -public class SavingProduct extends AbstractAuditableCustom { - - @Column(name = "name", nullable = false) - private String name; - - @Column(name = "description") - private String description; - - @Column(name = "is_deleted", nullable = false) - private boolean deleted = false; - - @Embedded - private final SavingProductRelatedDetail savingProductRelatedDetail; - - protected SavingProduct() { - this.name = null; - this.description = null; - this.savingProductRelatedDetail = null; - } - - public SavingProduct(final String name, final String description, final MonetaryCurrency currency, final BigDecimal interestRate, - final BigDecimal minInterestRate, final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount, - final Integer depositEvery, final SavingProductType savingProductType, final TenureTypeEnum tenureType, final Integer tenure, - final SavingFrequencyType savingFrequencyType, final SavingsInterestType savingsInterestType, - final SavingInterestCalculationMethod savingInterestCalculationMethod, final BigDecimal minimumBalanceForWithdrawal, - final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, - final PeriodFrequencyType lockinPeriodType) { - - this.name = name.trim(); - if (StringUtils.isNotBlank(description)) { - this.description = description.trim(); - } else { - this.description = null; - } - this.savingProductRelatedDetail = new SavingProductRelatedDetail(currency, interestRate, minInterestRate, maxInterestRate, - savingsDepositAmount, depositEvery, savingProductType, tenureType, tenure, savingFrequencyType, savingsInterestType, - savingInterestCalculationMethod, minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod, - lockinPeriodType); - } - - public String getName() { - return this.name; - } - - public String getDescription() { - return this.description; - } - - public MonetaryCurrency getCurrency() { - return this.savingProductRelatedDetail.getCurrency(); - } - - public BigDecimal getInterestRate() { - return this.savingProductRelatedDetail.getInterestRate(); - } - - public BigDecimal getMinimumBalance() { - return this.savingProductRelatedDetail.getMinimumBalance(); - } - - public boolean isDeleted() { - return deleted; - } - - public void delete() { - this.deleted = true; - } - - public SavingProductRelatedDetail getSavingProductRelatedDetail() { - return savingProductRelatedDetail; - } - - public Map update(final JsonCommand command) { - - final Map actualChanges = new LinkedHashMap(20); - - final String nameParamName = "name"; - if (command.isChangeInStringParameterNamed(nameParamName, this.name)) { - final String newValue = command.stringValueOfParameterNamed(nameParamName); - actualChanges.put(nameParamName, newValue); - this.name = newValue; - } - - final String descriptionParamName = "description"; - if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) { - final String newValue = command.stringValueOfParameterNamed(descriptionParamName); - actualChanges.put(descriptionParamName, newValue); - this.description = newValue; - } - - return this.savingProductRelatedDetail.update(command, actualChanges); - } - - public static SavingProduct assembleFromJson(final JsonCommand command, final MonetaryCurrency currency, - final SavingProductType savingProductType, final TenureTypeEnum tenureType, final SavingFrequencyType savingFrequencyType, - final SavingsInterestType interestType, final SavingInterestCalculationMethod savingInterestCalculationMethod, - final PeriodFrequencyType lockinPeriodType) { - - final String name = command.stringValueOfParameterNamed("name"); - final String description = command.stringValueOfParameterNamed("description"); - final BigDecimal interestRate = command.bigDecimalValueOfParameterNamed("interestRate"); - final BigDecimal minInterestRate = command.bigDecimalValueOfParameterNamed("minInterestRate"); - final BigDecimal maxInterestRate = command.bigDecimalValueOfParameterNamed("maxInterestRate"); - final BigDecimal savingsDepositAmount = command.bigDecimalValueOfParameterNamed("savingsDepositAmount"); - final Integer tenure = command.integerValueOfParameterNamed("tenure"); - final BigDecimal minimumBalanceForWithdrawal = command.bigDecimalValueOfParameterNamed("minimumBalanceForWithdrawal"); - final boolean isPartialDepositAllowed = command.booleanPrimitiveValueOfParameterNamed("isPartialDepositAllowed"); - final boolean isLockinPeriodAllowed = command.booleanPrimitiveValueOfParameterNamed("isLockinPeriodAllowed"); - final Integer lockinPeriod = command.integerValueOfParameterNamed("lockinPeriod"); - final Integer depositEvery = command.integerValueOfParameterNamed("depositEvery"); - - return new SavingProduct(name, description, currency, interestRate, minInterestRate, maxInterestRate, savingsDepositAmount, - depositEvery, savingProductType, tenureType, tenure, savingFrequencyType, interestType, savingInterestCalculationMethod, - minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRelatedDetail.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRelatedDetail.java deleted file mode 100644 index 678c4d044..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRelatedDetail.java +++ /dev/null @@ -1,310 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -import java.math.BigDecimal; -import java.util.Map; - -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Embedded; - -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; - -@Embeddable -public class SavingProductRelatedDetail { - - @Embedded - private MonetaryCurrency currency; - - @Column(name = "interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal interestRate; - - @SuppressWarnings("unused") - @Column(name = "min_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal minInterestRate; - - @SuppressWarnings("unused") - @Column(name = "max_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal maxInterestRate; - - @Column(name = "savings_deposit_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal savingsDepositAmount; - - @Column(name = "deposit_every") - private Integer depositEvery; - - @Column(name = "savings_product_type", nullable = false) - private Integer savingProductType; - - @Column(name = "tenure_type", nullable = false) - private Integer tenureType; - - @Column(name = "tenure", nullable = false) - private Integer tenure; - - @Column(name = "frequency", nullable = false) - private Integer frequency; - - @Column(name = "interest_type", nullable = false) - private Integer interestType; - - @Column(name = "interest_calculation_method") - private Integer interestCalculationMethod; - - @Column(name = "min_bal_for_withdrawal", scale = 6, precision = 19, nullable = false) - private BigDecimal minimumBalanceForWithdrawal; - - @Column(name = "is_partial_deposit_allowed", nullable = false) - private boolean isPartialDepositAllowed; - - @Column(name = "is_lock_in_period_allowed", nullable = false) - private boolean isLockinPeriodAllowed; - - @Column(name = "lock_in_period", nullable = false) - private Integer lockinPeriod; - - @Column(name = "lock_in_period_type", nullable = false) - private Integer lockinPeriodType; - - public SavingProductRelatedDetail() { - this.interestRate = null; - this.savingsDepositAmount = null; - } - - public SavingProductRelatedDetail(final MonetaryCurrency currency, final BigDecimal interestRate, final BigDecimal minInterestRate, - final BigDecimal maxInterestRate, final BigDecimal savingsDepositAmount, final Integer depositEvery, - final SavingProductType savingProductType, final TenureTypeEnum tenureType, final Integer tenure, - final SavingFrequencyType frequency, final SavingsInterestType interestType, - final SavingInterestCalculationMethod interestCalculationMethod, final BigDecimal minimumBalanceForWithdrawal, - final boolean isPartialDepositAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, - final PeriodFrequencyType lockinPeriodType) { - this.currency = currency; - this.interestRate = interestRate; - this.minInterestRate = minInterestRate; - this.maxInterestRate = maxInterestRate; - this.savingsDepositAmount = savingsDepositAmount; - this.depositEvery = depositEvery; - this.savingProductType = savingProductType.getValue(); - this.tenureType = tenureType.getValue(); - this.tenure = tenure; - this.frequency = frequency.getValue(); - this.interestType = interestType.getValue(); - this.interestCalculationMethod = interestCalculationMethod.getValue(); - this.minimumBalanceForWithdrawal = minimumBalanceForWithdrawal; - this.isPartialDepositAllowed = isPartialDepositAllowed; - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType.getValue(); - } - - public MonetaryCurrency getCurrency() { - return this.currency.copy(); - } - - public BigDecimal getInterestRate() { - return BigDecimal.valueOf(Double.valueOf(this.interestRate.stripTrailingZeros().toString())); - } - - public BigDecimal getMinimumBalance() { - return BigDecimal.valueOf(Double.valueOf(this.savingsDepositAmount.stripTrailingZeros().toString())); - } - - public Map update(final JsonCommand command, final Map actualChanges) { - - final String localeAsInput = command.locale(); - - Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal(); - final String digitsAfterDecimalParamName = "digitsAfterDecimal"; - if (command.isChangeInIntegerParameterNamed(digitsAfterDecimalParamName, digitsAfterDecimal)) { - final Integer newValue = command.integerValueOfParameterNamed(digitsAfterDecimalParamName); - actualChanges.put(digitsAfterDecimalParamName, newValue); - actualChanges.put("locale", localeAsInput); - digitsAfterDecimal = newValue; - this.currency = new MonetaryCurrency(this.currency.getCode(), digitsAfterDecimal); - } - - String currencyCode = this.currency.getCode(); - final String currencyCodeParamName = "currencyCode"; - if (command.isChangeInStringParameterNamed(currencyCodeParamName, currencyCode)) { - final String newValue = command.stringValueOfParameterNamed(currencyCodeParamName); - actualChanges.put(currencyCodeParamName, newValue); - currencyCode = newValue; - this.currency = new MonetaryCurrency(currencyCode, this.currency.getDigitsAfterDecimal()); - } - - final String interestRateParamName = "interestRate"; - if (command.isChangeInBigDecimalParameterNamed(interestRateParamName, this.interestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(interestRateParamName); - actualChanges.put(interestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestRate = newValue; - } - - final String savingsDepositAmountParamName = "savingsDepositAmount"; - if (command.isChangeInBigDecimalParameterNamed(savingsDepositAmountParamName, this.savingsDepositAmount)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(savingsDepositAmountParamName); - actualChanges.put(savingsDepositAmountParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.savingsDepositAmount = newValue; - } - - final String depositEveryParamName = "depositEvery"; - if (command.isChangeInIntegerParameterNamed(depositEveryParamName, this.depositEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(depositEveryParamName); - actualChanges.put(depositEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.depositEvery = newValue; - } - - final String savingProductTypeParamName = "savingProductType"; - if (command.isChangeInIntegerParameterNamed(savingProductTypeParamName, this.savingProductType)) { - final Integer newValue = command.integerValueOfParameterNamed(savingProductTypeParamName); - actualChanges.put(savingProductTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.savingProductType = SavingProductType.fromInt(newValue).getValue(); - } - - final String tenureTypeParamName = "tenureType"; - if (command.isChangeInIntegerParameterNamed(tenureTypeParamName, this.tenureType)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureTypeParamName); - actualChanges.put(tenureTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.tenureType = TenureTypeEnum.fromInt(newValue).getValue(); - } - - final String tenureParamName = "tenure"; - if (command.isChangeInIntegerParameterNamed(tenureParamName, this.tenure)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureParamName); - actualChanges.put(tenureParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.tenure = newValue; - } - - final String frequencyParamName = "frequency"; - if (command.isChangeInIntegerParameterNamed(frequencyParamName, this.frequency)) { - final Integer newValue = command.integerValueOfParameterNamed(frequencyParamName); - actualChanges.put(frequencyParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.frequency = SavingFrequencyType.fromInt(newValue).getValue(); - } - - final String interestTypeParamName = "interestType"; - if (command.isChangeInIntegerParameterNamed(interestTypeParamName, this.interestType)) { - final Integer newValue = command.integerValueOfParameterNamed(interestTypeParamName); - actualChanges.put(interestTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestType = SavingsInterestType.fromInt(newValue).getValue(); - } - - final String interestCalculationMethodParamName = "interestCalculationMethod"; - if (command.isChangeInIntegerParameterNamed(interestCalculationMethodParamName, this.interestCalculationMethod)) { - final Integer newValue = command.integerValueOfParameterNamed(interestCalculationMethodParamName); - actualChanges.put(interestCalculationMethodParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestCalculationMethod = SavingInterestCalculationMethod.fromInt(newValue).getValue(); - } - - final String minimumBalanceForWithdrawalParamName = "minimumBalanceForWithdrawal"; - if (command.isChangeInBigDecimalParameterNamed(minimumBalanceForWithdrawalParamName, this.minimumBalanceForWithdrawal)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(minimumBalanceForWithdrawalParamName); - actualChanges.put(minimumBalanceForWithdrawalParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.minimumBalanceForWithdrawal = newValue; - } - - final String isPartialDepositAllowedParamName = "isPartialDepositAllowed"; - if (command.isChangeInBooleanParameterNamed(isPartialDepositAllowedParamName, this.isPartialDepositAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isPartialDepositAllowedParamName); - actualChanges.put(isPartialDepositAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.isPartialDepositAllowed = newValue; - } - - final String isLockinPeriodAllowedParamName = "isLockinPeriodAllowed"; - if (command.isChangeInBooleanParameterNamed(isLockinPeriodAllowedParamName, this.isLockinPeriodAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isLockinPeriodAllowedParamName); - actualChanges.put(isLockinPeriodAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.isLockinPeriodAllowed = newValue; - } - - final String lockinPeriodParamName = "lockinPeriod"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodParamName, this.lockinPeriod)) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodParamName); - actualChanges.put(lockinPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.lockinPeriod = newValue; - } - - final String lockinPeriodTypeParamName = "lockinPeriodType"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodTypeParamName, this.lockinPeriodType)) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodTypeParamName); - actualChanges.put(lockinPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.lockinPeriodType = PeriodFrequencyType.fromInt(newValue).getValue(); - } - - return actualChanges; - - } - - public BigDecimal getSavingsDepositAmount() { - return savingsDepositAmount; - } - - public Integer getDepositEvery() { - return this.depositEvery; - } - - public Integer getSavingProductType() { - return savingProductType; - } - - public Integer getTenureType() { - return tenureType; - } - - public Integer getTenure() { - return tenure; - } - - public Integer getFrequency() { - return frequency; - } - - public Integer getInterestType() { - return interestType; - } - - public Integer getInterestCalculationMethod() { - return interestCalculationMethod; - } - - public BigDecimal getMinimumBalanceForWithdrawal() { - return minimumBalanceForWithdrawal; - } - - public boolean isPartialDepositAllowed() { - return isPartialDepositAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public Integer getLockinPeriodType() { - return lockinPeriodType; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRepository.java deleted file mode 100644 index 3d8d05f19..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -public interface SavingProductRepository extends JpaRepository, JpaSpecificationExecutor { - // -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductType.java deleted file mode 100644 index b3405e1a5..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingProductType.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -public enum SavingProductType { - - INVALID(0, "savingProductType.invalid"), // - RECURRING(1, "savingProductType.reccuring"), // - REGULAR(2, "savingProductType.regular"); - - private final Integer value; - private final String code; - - private SavingProductType(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public static SavingProductType fromInt(final Integer frequency) { - - SavingProductType savingProductType = SavingProductType.INVALID; - switch (frequency) { - case 1: - savingProductType = SavingProductType.RECURRING; - break; - case 2: - savingProductType = SavingProductType.REGULAR; - break; - default: - savingProductType = SavingProductType.INVALID; - break; - } - return savingProductType; - } - - public boolean isReccuring() { - return this.value.equals(SavingProductType.RECURRING.getValue()); - } - - public boolean isRegular() { - return this.value.equals(SavingProductType.REGULAR.getValue()); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsInterestType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsInterestType.java deleted file mode 100644 index eb1a3950d..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsInterestType.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -public enum SavingsInterestType { - - INVALID(0, "savingsInterestType.invalid"), // - SIMPLE(1, "savingsInterestType.simple"), // - COMPOUNDING(2, "savingsInterestType.compounding"); - - private final Integer value; - private final String code; - - private SavingsInterestType(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public static SavingsInterestType fromInt(final Integer frequency) { - - SavingsInterestType savingsInterestType = SavingsInterestType.INVALID; - switch (frequency) { - case 1: - savingsInterestType = SavingsInterestType.SIMPLE; - break; - case 2: - savingsInterestType = SavingsInterestType.COMPOUNDING; - break; - default: - savingsInterestType = SavingsInterestType.INVALID; - break; - } - return savingsInterestType; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsLockinPeriodEnum.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsLockinPeriodEnum.java deleted file mode 100644 index 6b3c85157..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/domain/SavingsLockinPeriodEnum.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.domain; - -public enum SavingsLockinPeriodEnum { - - DAYS(0, "lockin.period.type.days"), // - WEEKS(1, "lockin.period.type.weeks"), // - MONTHS(2, "lockin.period.type.months"), // - YEARS(3, "lockin.period.type.years"), // - INVALID(4, "lockin.period.type.invalid"); - - private final Integer value; - private final String code; - - private SavingsLockinPeriodEnum(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return this.value; - } - - public String getCode() { - return code; - } - - 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; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/UpdateSavingProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/UpdateSavingProductCommandHandler.java deleted file mode 100644 index b25f42831..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/handler/UpdateSavingProductCommandHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccountproduct.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingProductWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UpdateSavingProductCommandHandler implements NewCommandSourceHandler { - - private final SavingProductWritePlatformService savingProductWritePlatformService; - - @Autowired - public UpdateSavingProductCommandHandler(final SavingProductWritePlatformService savingProductWritePlatformService) { - this.savingProductWritePlatformService = savingProductWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingProductWritePlatformService.updateSavingProduct(command.entityId(), command); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/serialization/SavingProductCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/serialization/SavingProductCommandFromApiJsonDeserializer.java deleted file mode 100644 index be4f7f283..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/serialization/SavingProductCommandFromApiJsonDeserializer.java +++ /dev/null @@ -1,214 +0,0 @@ -package org.mifosplatform.portfolio.savingsaccountproduct.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public class SavingProductCommandFromApiJsonDeserializer { - - private final Set supportedParams = new HashSet(Arrays.asList("locale", "name", "description", "currencyCode", - "digitsAfterDecimal", "interestRate", "minInterestRate", "maxInterestRate", "savingsDepositAmount", "savingProductType", - "tenureType", "tenure", "frequency", "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal", - "isPartialDepositAllowed", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "depositEvery")); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public SavingProductCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForCreate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("product"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final String name = fromApiJsonHelper.extractStringNamed("name", element); - baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - - final String description = fromApiJsonHelper.extractStringNamed("description", element); - baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500); - - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); - baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank(); - - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); - baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); - - final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRate", element); - baseDataValidator.reset().parameter("interestRate").value(interestRate).notNull().zeroOrPositiveAmount(); - - final BigDecimal minInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minInterestRate", element); - baseDataValidator.reset().parameter("minInterestRate").value(minInterestRate).notNull().zeroOrPositiveAmount(); - - final BigDecimal maxInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxInterestRate", element); - baseDataValidator.reset().parameter("maxInterestRate").value(maxInterestRate).notNull().zeroOrPositiveAmount(); - - baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, maxInterestRate); - baseDataValidator.reset().parameter("interestRate").comapareMinAndMaxOfTwoBigDecmimalNos(interestRate, maxInterestRate); - baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, interestRate); - - final BigDecimal savingsDepositAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingsDepositAmount", element); - baseDataValidator.reset().parameter("savingsDepositAmount").value(savingsDepositAmount).notNull().zeroOrPositiveAmount(); - - final Integer savingProductType = fromApiJsonHelper.extractIntegerNamed("savingProductType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("savingProductType").value(savingProductType).notNull(); - - final Integer tenureType = fromApiJsonHelper.extractIntegerNamed("tenureType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureType").value(tenureType).notNull(); - - final Integer tenure = fromApiJsonHelper.extractIntegerNamed("tenure", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenure").value(tenure).notNull(); - - final Integer frequency = fromApiJsonHelper.extractIntegerNamed("frequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("frequency").value(frequency).notNull(); - - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestType").value(interestType).notNull(); - - final Integer interestCalculationMethod = fromApiJsonHelper.extractIntegerNamed("interestCalculationMethod", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCalculationMethod").value(interestCalculationMethod).notNull(); - - final BigDecimal minimumBalanceForWithdrawal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minimumBalanceForWithdrawal", - element); - baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(minimumBalanceForWithdrawal).notNull() - .zeroOrPositiveAmount(); - - final Boolean isPartialDepositAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isPartialDepositAllowed", element); - baseDataValidator.reset().parameter("isPartialDepositAllowed").value(isPartialDepositAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isPartialDepositAllowedCommandValue)).notNull(); - - final Boolean isLockinPeriodAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(isLockinPeriodAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).notNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).notNull().inMinMaxRange(1, 3); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - - public void validateForUpdate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("product"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final String name = fromApiJsonHelper.extractStringNamed("name", element); - baseDataValidator.reset().parameter("name").value(name).ignoreIfNull().notBlank().notExceedingLengthOf(100); - - final String description = fromApiJsonHelper.extractStringNamed("description", element); - baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500); - - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); - baseDataValidator.reset().parameter("currencyCode").value(currencyCode).ignoreIfNull().notBlank(); - - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); - baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).ignoreIfNull().inMinMaxRange(0, 6); - - final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRate", element); - baseDataValidator.reset().parameter("interestRate").value(interestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal minInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minInterestRate", element); - baseDataValidator.reset().parameter("minInterestRate").value(minInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal maxInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxInterestRate", element); - baseDataValidator.reset().parameter("maxInterestRate").value(maxInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, maxInterestRate); - baseDataValidator.reset().parameter("interestRate").comapareMinAndMaxOfTwoBigDecmimalNos(interestRate, maxInterestRate); - baseDataValidator.reset().parameter("minInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, interestRate); - - final BigDecimal savingsDepositAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("savingsDepositAmount", element); - baseDataValidator.reset().parameter("savingsDepositAmount").value(savingsDepositAmount).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer savingProductType = fromApiJsonHelper.extractIntegerNamed("savingProductType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("savingProductType").value(savingProductType).ignoreIfNull(); - - final Integer tenureType = fromApiJsonHelper.extractIntegerNamed("tenureType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureType").value(tenureType).ignoreIfNull(); - - final Integer tenure = fromApiJsonHelper.extractIntegerNamed("tenure", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenure").value(tenure).ignoreIfNull().integerGreaterThanZero(); - - final Integer frequency = fromApiJsonHelper.extractIntegerNamed("frequency", element, Locale.getDefault()); - baseDataValidator.reset().parameter("frequency").value(frequency).ignoreIfNull(); - - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestType").value(interestType).ignoreIfNull(); - - final Integer interestCalculationMethod = fromApiJsonHelper.extractIntegerNamed("interestCalculationMethod", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCalculationMethod").value(interestCalculationMethod).ignoreIfNull(); - - final BigDecimal minimumBalanceForWithdrawal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minimumBalanceForWithdrawal", - element); - baseDataValidator.reset().parameter("minimumBalanceForWithdrawal").value(minimumBalanceForWithdrawal).ignoreIfNull() - .zeroOrPositiveAmount(); - - final Boolean isPartialDepositAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isPartialDepositAllowed", element); - baseDataValidator.reset().parameter("isPartialDepositAllowed").value(isPartialDepositAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isPartialDepositAllowedCommandValue)).ignoreIfNull(); - - final Boolean isLockinPeriodAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(isLockinPeriodAllowedCommandValue) - .trueOrFalseRequired(isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)).ignoreIfNull(); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - - private Boolean isBooleanValueUpdated(final Boolean actualValue) { - Boolean isUpdated = false; - if (actualValue != null) { - isUpdated = true; - } - return isUpdated; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductEnumerations.java deleted file mode 100644 index 349ffea7c..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductEnumerations.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.service; - -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsLockinPeriodEnum; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; - -public class SavingProductEnumerations { - - public static EnumOptionData savingProductType(final int id) { - return savingProductType(SavingProductType.fromInt(id)); - } - - public static EnumOptionData tenureTypeEnum(final int id) { - return tenureTypeEnum(TenureTypeEnum.fromInt(id)); - } - - public static EnumOptionData interestFrequencyType(final int id) { - return interestFrequencyType(SavingFrequencyType.fromInt(id)); - } - - public static EnumOptionData savingInterestType(final int id) { - return savingInterestType(SavingsInterestType.fromInt(id)); - } - - public static EnumOptionData savingInterestCalculationMethod(final int id) { - return savingInterestCalculationMethod(SavingInterestCalculationMethod.fromInt(id)); - } - - public static EnumOptionData savingsLockinPeriod(final int id) { - return savingsLockinPeriod(SavingsLockinPeriodEnum.fromInt(id)); - } - - public static EnumOptionData savingsLockinPeriod(final SavingsLockinPeriodEnum type) { - final String codePrefix = "savings.product."; - EnumOptionData optionData = null; - switch (type) { - case DAYS: - optionData = new EnumOptionData(SavingsLockinPeriodEnum.DAYS.getValue().longValue(), codePrefix - + SavingsLockinPeriodEnum.DAYS.getCode(), "Days"); - break; - case MONTHS: - optionData = new EnumOptionData(SavingsLockinPeriodEnum.MONTHS.getValue().longValue(), codePrefix - + SavingsLockinPeriodEnum.MONTHS.getCode(), "Months"); - break; - case WEEKS: - optionData = new EnumOptionData(SavingsLockinPeriodEnum.WEEKS.getValue().longValue(), codePrefix - + SavingsLockinPeriodEnum.WEEKS.getCode(), "Weeks"); - break; - case YEARS: - optionData = new EnumOptionData(SavingsLockinPeriodEnum.YEARS.getValue().longValue(), codePrefix - + SavingsLockinPeriodEnum.YEARS.getCode(), "Years"); - break; - default: - optionData = new EnumOptionData(SavingsLockinPeriodEnum.INVALID.getValue().longValue(), codePrefix - + SavingsLockinPeriodEnum.INVALID.getCode(), "Invalid"); - break; - } - return optionData; - } - - public static EnumOptionData savingInterestCalculationMethod(final SavingInterestCalculationMethod type) { - final String codePrefix = "savings.interestCalculation.method."; - EnumOptionData optionData = null; - switch (type) { - case MINBAL: - optionData = new EnumOptionData(SavingInterestCalculationMethod.MINBAL.getValue().longValue(), codePrefix - + SavingInterestCalculationMethod.MINBAL.getCode(), "Minimumbalance"); - break; - case AVERAGEBAL: - optionData = new EnumOptionData(SavingInterestCalculationMethod.AVERAGEBAL.getValue().longValue(), codePrefix - + SavingInterestCalculationMethod.AVERAGEBAL.getCode(), "AverageBalance"); - break; - case INVALID: - optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix - + SavingInterestCalculationMethod.INVALID.getCode(), "Invalid"); - break; - case MONTHLYCOLLECTION: - optionData = new EnumOptionData(SavingInterestCalculationMethod.MONTHLYCOLLECTION.getValue().longValue(), codePrefix - + SavingInterestCalculationMethod.MONTHLYCOLLECTION.getCode(), "MonthlyCollection"); - break; - default: - optionData = new EnumOptionData(SavingInterestCalculationMethod.INVALID.getValue().longValue(), codePrefix - + SavingInterestCalculationMethod.INVALID.getCode(), "Invalid"); - break; - } - return optionData; - } - - public static EnumOptionData savingInterestType(final SavingsInterestType type) { - final String codePrefix = "savings.interest.type."; - EnumOptionData optionData = null; - switch (type) { - case COMPOUNDING: - optionData = new EnumOptionData(SavingsInterestType.COMPOUNDING.getValue().longValue(), codePrefix - + SavingsInterestType.COMPOUNDING.getCode(), "Compounding"); - break; - case SIMPLE: - optionData = new EnumOptionData(SavingsInterestType.SIMPLE.getValue().longValue(), codePrefix - + SavingsInterestType.SIMPLE.getCode(), "Simple"); - break; - default: - optionData = new EnumOptionData(SavingsInterestType.INVALID.getValue().longValue(), codePrefix - + SavingsInterestType.INVALID.getCode(), "Invalid"); - break; - } - return optionData; - } - - public static EnumOptionData interestFrequencyType(final SavingFrequencyType type) { - final String codePrefix = "saving.product.frequency.period."; - EnumOptionData optionData = null; - switch (type) { - case DAILY: - optionData = new EnumOptionData(SavingFrequencyType.DAILY.getValue().longValue(), codePrefix - + SavingFrequencyType.DAILY.getCode(), "Days"); - break; - case MONTHLY: - optionData = new EnumOptionData(SavingFrequencyType.MONTHLY.getValue().longValue(), codePrefix - + SavingFrequencyType.MONTHLY.getCode(), "Months"); - break; - case QUATERLY: - optionData = new EnumOptionData(SavingFrequencyType.QUATERLY.getValue().longValue(), codePrefix - + SavingFrequencyType.QUATERLY.getCode(), "Months"); - break; - case HALFYEARLY: - optionData = new EnumOptionData(SavingFrequencyType.HALFYEARLY.getValue().longValue(), codePrefix - + SavingFrequencyType.HALFYEARLY.getCode(), "Months"); - break; - case YEARLY: - optionData = new EnumOptionData(SavingFrequencyType.YEARLY.getValue().longValue(), codePrefix - + SavingFrequencyType.YEARLY.getCode(), "Yearly"); - break; - default: - optionData = new EnumOptionData(SavingFrequencyType.INVALID.getValue().longValue(), SavingFrequencyType.INVALID.getCode(), - "Invalid"); - break; - } - return optionData; - } - - public static EnumOptionData tenureTypeEnum(final TenureTypeEnum type) { - final String codePrefix = "savings.tenure."; - EnumOptionData optionData = null; - switch (type) { - case FIXED_PERIOD: - optionData = new EnumOptionData(TenureTypeEnum.FIXED_PERIOD.getValue().longValue(), codePrefix - + TenureTypeEnum.FIXED_PERIOD.getCode(), "FixedPeriod"); - break; - case PERPETUAL: - optionData = new EnumOptionData(TenureTypeEnum.PERPETUAL.getValue().longValue(), codePrefix - + TenureTypeEnum.PERPETUAL.getCode(), "Perpetual"); - break; - default: - optionData = new EnumOptionData(TenureTypeEnum.INVALID.getValue().longValue(), codePrefix - + TenureTypeEnum.INVALID.getCode(), "Invalid"); - break; - } - return optionData; - } - - public static EnumOptionData savingProductType(final SavingProductType type) { - final String codePrefix = "savings.product."; - EnumOptionData optionData = null; - switch (type) { - case RECURRING: - optionData = new EnumOptionData(SavingProductType.RECURRING.getValue().longValue(), codePrefix - + SavingProductType.RECURRING.getCode(), "Recurring"); - break; - case REGULAR: - optionData = new EnumOptionData(SavingProductType.REGULAR.getValue().longValue(), codePrefix - + SavingProductType.REGULAR.getCode(), "Regular"); - break; - case INVALID: - optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), codePrefix - + SavingProductType.INVALID.getCode(), "Invalid"); - break; - default: - optionData = new EnumOptionData(SavingProductType.INVALID.getValue().longValue(), SavingProductType.INVALID.getCode(), - "Invalid"); - break; - } - return optionData; - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformService.java deleted file mode 100644 index e7a60cce8..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformService.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.service; - -import java.util.Collection; - -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductData; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductLookup; - -public interface SavingProductReadPlatformService { - - Collection retrieveAllSavingProducts(); - - Collection retrieveAllSavingProductsForLookup(); - - SavingProductData retrieveSavingProduct(Long productId); - - SavingProductData retrieveNewSavingProductDetails(); -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformServiceImpl.java deleted file mode 100644 index 0c2467018..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductReadPlatformServiceImpl.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.service; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; - -import org.joda.time.DateTime; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.domain.JdbcSupport; -import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.organisation.monetary.service.CurrencyReadPlatformService; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductData; -import org.mifosplatform.portfolio.savingsaccountproduct.data.SavingProductLookup; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.exception.SavingProductNotFoundException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Service; - -@Service -public class SavingProductReadPlatformServiceImpl implements SavingProductReadPlatformService { - - private final PlatformSecurityContext context; - private final JdbcTemplate jdbcTemplate; - private final CurrencyReadPlatformService currencyReadPlatformService; - - @Autowired - public SavingProductReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource, - final CurrencyReadPlatformService currencyReadPlatformService) { - - this.context = context; - jdbcTemplate = new JdbcTemplate(dataSource); - this.currencyReadPlatformService = currencyReadPlatformService; - } - - @Override - public Collection retrieveAllSavingProducts() { - - this.context.authenticatedUser(); - - SavingProductMapper savingProductMapper = new SavingProductMapper(); - - String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.is_deleted=0"; - - return this.jdbcTemplate.query(sql, savingProductMapper, new Object[] {}); - - } - - @Override - public Collection retrieveAllSavingProductsForLookup() { - - this.context.authenticatedUser(); - - SavingProductLookupMapper savingProductLookupMapper = new SavingProductLookupMapper(); - - String sql = "select " + savingProductLookupMapper.savingProductLookupSchema() + " where sp.is_deleted=0"; - - return this.jdbcTemplate.query(sql, savingProductLookupMapper, new Object[] {}); - } - - @Override - public SavingProductData retrieveSavingProduct(Long savingProductId) { - try { - this.context.authenticatedUser(); - SavingProductMapper savingProductMapper = new SavingProductMapper(); - String sql = "select " + savingProductMapper.savingProductSchema() + " where sp.id = ? and sp.is_deleted=0"; - SavingProductData productData = this.jdbcTemplate.queryForObject(sql, savingProductMapper, new Object[] { savingProductId }); - - populateProductDataWithDropdownOptions(productData); - - return productData; - } catch (EmptyResultDataAccessException e) { - throw new SavingProductNotFoundException(savingProductId); - } - } - - @Override - public SavingProductData retrieveNewSavingProductDetails() { - - SavingProductData productData = new SavingProductData(); - - populateProductDataWithDropdownOptions(productData); - - return productData; - } - - private static final class SavingProductMapper implements RowMapper { - - public String savingProductSchema() { - return "sp.id as id,sp.name as name, sp.description as description,sp.currency_code as currencyCode, sp.currency_digits as currencyDigits,sp.interest_rate as interestRate, " - + "sp.min_interest_rate as minInterestRate, sp.max_interest_rate as maxInterstRate, sp.deposit_every as depositEvery, " - + " sp.savings_deposit_amount as savingsDepositAmount, sp.savings_product_type as savingProductType, sp.tenure_type as tenureType, sp.tenure as tenure, sp.frequency as frequency, " - + " sp.interest_type as interestType, sp.interest_calculation_method as interestCalculationMethod, sp.min_bal_for_withdrawal as minimumBalanceForWithdrawal, " - + " sp.is_partial_deposit_allowed as isPartialDepositAllowed, sp.is_lock_in_period_allowed as isLockinPeriodAllowed, sp.lock_in_period as lockinPeriod, sp.lock_in_period_type as lockinPeriodType, " - + " sp.created_date as createdon, sp.lastmodified_date as modifiedon, " - + "curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol" - + " from m_product_savings sp join m_currency curr on curr.code = sp.currency_code"; - } - - @Override - public SavingProductData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - - Long id = rs.getLong("id"); - String name = rs.getString("name"); - String description = rs.getString("description"); - - String currencyCode = rs.getString("currencyCode"); - String currencyName = rs.getString("currencyName"); - String currencyNameCode = rs.getString("currencyNameCode"); - String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); - Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); - - CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, - currencyNameCode); - BigDecimal interestRate = rs.getBigDecimal("interestRate"); - BigDecimal minInterestRate = rs.getBigDecimal("minInterestRate"); - BigDecimal maxInterestRate = rs.getBigDecimal("maxInterstRate"); - - DateTime createdOn = JdbcSupport.getDateTime(rs, "createdon"); - DateTime lastModifedOn = JdbcSupport.getDateTime(rs, "modifiedon"); - - Integer depositEvery = JdbcSupport.getInteger(rs, "depositEvery"); - BigDecimal savingsDepositAmount = rs.getBigDecimal("savingsDepositAmount"); - EnumOptionData savingProductTypeEnum = SavingProductEnumerations.savingProductType(SavingProductType.fromInt(JdbcSupport - .getInteger(rs, "savingProductType"))); - EnumOptionData tenureTypeEnum = SavingProductEnumerations.tenureTypeEnum(JdbcSupport.getInteger(rs, "tenureType")); - Integer tenure = JdbcSupport.getInteger(rs, "tenure"); - EnumOptionData savingFrequencyType = SavingProductEnumerations.interestFrequencyType(JdbcSupport.getInteger(rs, "frequency")); - EnumOptionData savingInterestType = SavingProductEnumerations.savingInterestType(JdbcSupport.getInteger(rs, "interestType")); - EnumOptionData interestCalculationMethodEnum = SavingProductEnumerations.savingInterestCalculationMethod(JdbcSupport - .getInteger(rs, "interestCalculationMethod")); - BigDecimal minimumBalanceForWithdrawal = rs.getBigDecimal("minimumBalanceForWithdrawal"); - boolean isPartialDepositAllowed = rs.getBoolean("isPartialDepositAllowed"); - boolean isLockinPeriodAllowed = rs.getBoolean("isLockinPeriodAllowed"); - Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod"); - EnumOptionData lockinPeriodType = SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType - .fromInt(JdbcSupport.getInteger(rs, "lockinPeriodType"))); - - return new SavingProductData(createdOn, lastModifedOn, id, name, description, interestRate, minInterestRate, maxInterestRate, - currencyData, currencyDigits, savingsDepositAmount, savingProductTypeEnum, tenureTypeEnum, tenure, savingFrequencyType, - savingInterestType, interestCalculationMethodEnum, minimumBalanceForWithdrawal, isPartialDepositAllowed, - isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, depositEvery); - } - } - - private static final class SavingProductLookupMapper implements RowMapper { - - public String savingProductLookupSchema() { - return " sp.id as id, sp.name as name from m_product_savings sp"; - } - - @Override - public SavingProductLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - Long id = rs.getLong("id"); - String name = rs.getString("name"); - - return new SavingProductLookup(id, name); - } - - } - - private void populateProductDataWithDropdownOptions(final SavingProductData productData) { - - Collection currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies(); - productData.setCurrencyOptions(currencyOptions); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformServiceJpaRepositoryImpl.java deleted file mode 100644 index 51bddcdca..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingProductWritePlatformServiceJpaRepositoryImpl.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.service; - -import java.util.Map; - -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; -import org.mifosplatform.infrastructure.security.exception.NoAuthorizationException; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingInterestCalculationMethod; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProduct; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductRepository; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingProductType; -import org.mifosplatform.portfolio.savingsaccountproduct.domain.SavingsInterestType; -import org.mifosplatform.portfolio.savingsaccountproduct.exception.SavingProductNotFoundException; -import org.mifosplatform.portfolio.savingsaccountproduct.serialization.SavingProductCommandFromApiJsonDeserializer; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.TenureTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class SavingProductWritePlatformServiceJpaRepositoryImpl implements SavingProductWritePlatformService { - - private final PlatformSecurityContext context; - private final SavingProductRepository savingProductRepository; - private final SavingProductCommandFromApiJsonDeserializer fromApiJsonDeserializer; - - @Autowired - public SavingProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final SavingProductRepository savingProductRepository, final SavingProductCommandFromApiJsonDeserializer fromApiJsonDeserializer) { - this.context = context; - this.savingProductRepository = savingProductRepository; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; - } - - @Transactional - @Override - public CommandProcessingResult createSavingProduct(final JsonCommand command) { - - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForCreate(command.json()); - - final Integer savingProductTypeCommandValue = command.integerValueOfParameterNamed("savingProductType"); - SavingProductType savingProductType = SavingProductType.fromInt(savingProductTypeCommandValue); - final Integer tenureTypeCommandValue = command.integerValueOfParameterNamed("tenureType"); - TenureTypeEnum tenureType = TenureTypeEnum.fromInt(tenureTypeCommandValue); - final Integer frequencyCommandValue = command.integerValueOfParameterNamed("frequency"); - SavingFrequencyType savingFrequencyType = SavingFrequencyType.fromInt(frequencyCommandValue); - final Integer interestTypeCommandValue = command.integerValueOfParameterNamed("interestType"); - SavingsInterestType interestType = SavingsInterestType.fromInt(interestTypeCommandValue); - final Integer lockinPeriodTypeCommandValue = command.integerValueOfParameterNamed("lockinPeriodType"); - PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.fromInt(lockinPeriodTypeCommandValue); - final Integer interestCalculationMethodCommandValue = command.integerValueOfParameterNamed("interestCalculationMethod"); - SavingInterestCalculationMethod savingInterestCalculationMethod = SavingInterestCalculationMethod - .fromInt(interestCalculationMethodCommandValue); - final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); - final Integer digitsAfterDecimal = command.integerValueOfParameterNamed("digitsAfterDecimal"); - MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal); - - if (savingProductType.equals(SavingProductType.INVALID) || tenureType.equals(TenureTypeEnum.INVALID) - || savingFrequencyType.equals(SavingFrequencyType.INVALID) || interestType.equals(SavingsInterestType.INVALID) - || lockinPeriodType.equals(PeriodFrequencyType.INVALID) - || savingInterestCalculationMethod.equals(SavingInterestCalculationMethod.INVALID)) { - throw new NoAuthorizationException("Please select a valid types"); } - - SavingProduct product = SavingProduct.assembleFromJson(command, currency, savingProductType, tenureType, savingFrequencyType, - interestType, savingInterestCalculationMethod, lockinPeriodType); - - this.savingProductRepository.save(product); - return new CommandProcessingResultBuilder() // - .withEntityId(product.getId()) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult updateSavingProduct(final Long productId, final JsonCommand command) { - - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForUpdate(command.json()); - - final SavingProduct product = this.savingProductRepository.findOne(productId); - - if (product == null || product.isDeleted()) { throw new SavingProductNotFoundException(productId); } - - final Map changes = product.update(command); - - this.savingProductRepository.save(product); - - return new CommandProcessingResultBuilder() // - .withEntityId(product.getId()) // - .with(changes).build(); - } - - @Transactional - @Override - public CommandProcessingResult deleteSavingProduct(final Long productId) { - - this.context.authenticatedUser(); - SavingProduct product = this.savingProductRepository.findOne(productId); - if (product == null || product.isDeleted()) { throw new SavingProductNotFoundException(productId); } - product.delete(); - this.savingProductRepository.save(product); - return new CommandProcessingResultBuilder() // - .withEntityId(product.getId()) // - .build(); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingsDepositEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingsDepositEnumerations.java deleted file mode 100644 index 945d4e760..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsaccountproduct/service/SavingsDepositEnumerations.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsaccountproduct.service; - -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; - -public class SavingsDepositEnumerations { - - public static EnumOptionData interestCompoundingPeriodType(final int id) { - return interestCompoundingPeriodType(PeriodFrequencyType.fromInt(id)); - } - - public static EnumOptionData interestCompoundingPeriodType(final PeriodFrequencyType type) { - final String codePrefix = "deposit.interest.compounding.period."; - EnumOptionData optionData = null; - switch (type) { - case DAYS: - optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + PeriodFrequencyType.DAYS.getCode(), "Days"); - break; - case WEEKS: - optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + PeriodFrequencyType.WEEKS.getCode(), "Weeks"); - break; - case MONTHS: - optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + PeriodFrequencyType.MONTHS.getCode(), "Months"); - break; - default: - optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), - "Invalid"); - break; - } - return optionData; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/api/DepositAccountsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/api/DepositAccountsApiResource.java deleted file mode 100644 index c803973b3..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/api/DepositAccountsApiResource.java +++ /dev/null @@ -1,281 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.api; - -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.UriInfo; - -import org.apache.commons.lang.StringUtils; -import org.mifosplatform.commands.domain.CommandWrapper; -import org.mifosplatform.commands.service.CommandWrapperBuilder; -import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; -import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; -import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; -import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; -import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingsDepositEnumerations; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountData; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountsForLookup; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositPermissionData; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountReadPlatformService; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.mifosplatform.portfolio.savingsdepositaccount.service.GeneratePDF; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductLookup; -import org.mifosplatform.portfolio.savingsdepositproduct.service.DepositProductReadPlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -@Path("/depositaccounts") -@Component -@Scope("singleton") -public class DepositAccountsApiResource { - - private static final Set SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS = new HashSet(Arrays.asList("productOptions", - "interestCompoundedEveryPeriodTypeOptions", "id", "externalId", "clientId", "clientName", "productId", "productName", "status", - "currency", "deposit", "maturityInterestRate", "tenureInMonths", "interestCompoundedEvery", - "interestCompoundedEveryPeriodType", "renewalAllowed", "preClosureAllowed", "preClosureInterestRate", "withdrawnonDate", - "rejectedonDate", "closedonDate", "transactions", "permissions", "isInterestWithdrawable", "interestPaid", - "interestCompoundingAllowed", "availableInterestForWithdrawal", "availableWithdrawalAmount", "todaysDate", - "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", "printFDdetailsLocation", "availableInterest", - "interestPostedAmount", "lastInterestPostedDate", "nextInterestPostedDate", "fatherName", "address", "imageKey")); - - private final DepositAccountReadPlatformService depositAccountReadPlatformService; - - private final DepositProductReadPlatformService depositProductReadPlatformService; - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - private final String entityType = "DEPOSITACCOUNT"; - - private final PlatformSecurityContext context; - - private final DefaultToApiJsonSerializer toApiJsonSerializer; - - private final ApiRequestParameterHelper apiRequestParameterHelper; - - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - - @Autowired - public DepositAccountsApiResource(final DepositAccountReadPlatformService depositAccountReadPlatformService, - final DepositProductReadPlatformService depositProductReadPlatformService, - final DepositAccountWritePlatformService depositAccountWritePlatformService, - final PlatformSecurityContext context, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService ) { - this.depositAccountReadPlatformService = depositAccountReadPlatformService; - this.depositProductReadPlatformService = depositProductReadPlatformService; - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - this.context = context; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - } - - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String createDepositAccount(final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().createDepositAccount().withJson(apiRequestBodyAsJson).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - } - - @PUT - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateDepositAccount(@PathParam("accountId") final Long accountId, final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDepositAccount(accountId).withJson(apiRequestBodyAsJson).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - } - - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAllDepositAccounts(@Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - Collection accounts = this.depositAccountReadPlatformService.retrieveAllDepositAccounts(); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - return this.toApiJsonSerializer.serialize(settings, accounts, SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS); - } - - @GET - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveDepositAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - DepositPermissionData permissions = null; - - DepositAccountData account = this.depositAccountReadPlatformService.retrieveDepositAccount(accountId); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - if (settings.isTemplate()) { - account = handleTemplateRelatedData(account); - } - - Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); - if (!associationParameters.isEmpty()) { - if (associationParameters.contains("all")) { - permissions = this.depositAccountReadPlatformService.retrieveDepositAccountsPermissions(account); - account = new DepositAccountData(account, permissions, account.getTransactions()); - } - } - - return this.toApiJsonSerializer.serialize(settings, account, SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS); - } - - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveNewDepositAccountDetails(@QueryParam("clientId") final Long clientId, - @QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) { - - context.authenticatedUser().validateHasReadPermission(entityType); - - DepositAccountData account = this.depositAccountReadPlatformService.retrieveNewDepositAccountDetails(clientId, productId); - - account = handleTemplateRelatedData(account); - - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - return this.toApiJsonSerializer.serialize(settings, account, SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS); - } - - @DELETE - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String deleteProduct(@PathParam("accountId") final Long accountId) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteDepositAccount(accountId).build(); - - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - } - - private DepositAccountData handleTemplateRelatedData(final DepositAccountData account) { - - Collection productOptions = depositProductReadPlatformService.retrieveAllDepositProductsForLookup(); - - EnumOptionData monthly = SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType.MONTHS); - List interestCompoundedEveryPeriodTypeOptions = Arrays.asList(monthly); - - return new DepositAccountData(account, interestCompoundedEveryPeriodTypeOptions, productOptions); - } - - @POST - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String SubmitDepositApplication(@PathParam("accountId") final Long accountId, - @QueryParam("command") final String commandParam, final String apiRequestBodyAsJson) { - - CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); - CommandProcessingResult result = null; - - if (is(commandParam, "approve")) { - final CommandWrapper commandRequest = builder.approveDepositApplication(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "withdrawal")) { - final CommandWrapper commandRequest = builder.withdrawDepositAmount(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "interestwithdraw")) { - final CommandWrapper commandRequest = builder.withdrawInterestDepositAmount(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "renew")) { - final CommandWrapper commandRequest = builder.renewDepositAccount(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "reject")) { - final CommandWrapper commandRequest = builder.rejectDepositAccount(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "withdrewbyclient")) { - final CommandWrapper commandRequest = builder.withdrawDepositApplication(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "undoapproval")) { - final CommandWrapper commandRequest = builder.undoDepositApplicationApproval(accountId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else { throw new UnrecognizedQueryParamException("command", commandParam); } - - return this.toApiJsonSerializer.serialize(result); - } - - private boolean is(final String commandParam, final String commandValue) { - return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); - } - - @POST - @Path("postinterest") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String postInterest() { - Collection accounts = this.depositAccountReadPlatformService.retrieveDepositAccountForLookup(); - CommandProcessingResult entityIdentifier = this.depositAccountWritePlatformService.postInterestToDepositAccount(accounts); - return this.toApiJsonSerializer.serialize(entityIdentifier); - - } - - @SuppressWarnings("null") - @GET - @Path("{accountId}/print") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response printDepositAccount(@PathParam("accountId") final Long accountId) { - - DepositAccountData account = this.depositAccountReadPlatformService.retrieveDepositAccount(accountId); - String printFileName = null; - if (account != null) printFileName = new GeneratePDF(account).generatePDF(); - account.setPrintFDdetailsLocation(printFileName); - - File file = new File(printFileName); - ResponseBuilder response = Response.ok(file); - response.header("Content-Disposition", "attachment; filename=\"" + printFileName + "\""); - response.header("Content-Type", "applicatio/pdf"); - return response.build(); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommand.java deleted file mode 100644 index 5dcb9ad1b..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommand.java +++ /dev/null @@ -1,200 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.math.BigDecimal; -import java.util.Set; - -import org.joda.time.LocalDate; - -/** - * Immutable command used when create/renewing deposit accounts - */ -public class DepositAccountCommand { - - private final Long id; - private final Long clientId; - private final Long productId; - private final String externalId; - - private final BigDecimal depositAmount; - private final BigDecimal maturityInterestRate; - private final BigDecimal preClosureInterestRate; - private final Integer tenureInMonths; - - private final boolean isLockinPeriodAllowed; - private final Integer lockinPeriod; - private final Integer lockinPeriodType; - - private final Integer interestCompoundedEvery; - private final Integer interestCompoundedEveryPeriodType; - private final LocalDate commencementDate; - - private final boolean renewalAllowed; - private final boolean preClosureAllowed; - private final boolean isInterestWithdrawable; - private final boolean interestCompoundingAllowed; - - private final Set modifiedParameters; - - public DepositAccountCommand(final Set modifiedParameters, final Long id, final Long clientId, final Long productId, - final String externalId, final BigDecimal depositAmount, final BigDecimal interestRate, - final BigDecimal preClosureInterestRate, final Integer tenureInMonths, final Integer compoundingInterestFrequency, - final Integer compoundingInterestFrequencyType, final LocalDate commencementDate, final boolean renewalAllowed, - final boolean preClosureAllowed, final boolean isInterstWithdrawable, final boolean interestCompoundingAllowed, - final boolean isLockinPeriodAllowed, final Integer lockInPeriod, final Integer lockinPeriodType) { - this.id = id; - this.clientId = clientId; - this.productId = productId; - this.externalId = externalId; - - this.depositAmount = depositAmount; - this.maturityInterestRate = interestRate; - this.preClosureInterestRate = preClosureInterestRate; - this.tenureInMonths = tenureInMonths; - - this.modifiedParameters = modifiedParameters; - this.interestCompoundedEvery = compoundingInterestFrequency; - this.interestCompoundedEveryPeriodType = compoundingInterestFrequencyType; - this.commencementDate = commencementDate; - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - this.isInterestWithdrawable = isInterstWithdrawable; - this.interestCompoundingAllowed = interestCompoundingAllowed; - - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockInPeriod; - this.lockinPeriodType = lockinPeriodType; - } - - public Long getId() { - return id; - } - - public Long getClientId() { - return clientId; - } - - public Long getProductId() { - return productId; - } - - public String getExternalId() { - return externalId; - } - - public BigDecimal getDepositAmount() { - return depositAmount; - } - - public BigDecimal getMaturityInterestRate() { - return maturityInterestRate; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public Integer getInterestCompoundedEvery() { - return interestCompoundedEvery; - } - - public Integer getInterestCompoundedEveryPeriodType() { - return interestCompoundedEveryPeriodType; - } - - public LocalDate getCommencementDate() { - return commencementDate; - } - - public boolean isInterestWithdrawable() { - return isInterestWithdrawable; - } - - public boolean isRenewalAllowed() { - return renewalAllowed; - } - - public boolean isPreClosureAllowed() { - return preClosureAllowed; - } - - public boolean isInterestCompoundingAllowed() { - return interestCompoundingAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public Integer getLockinPeriodType() { - return lockinPeriodType; - } - - public boolean isNoFieldChanged() { - return this.modifiedParameters.isEmpty(); - } - - public boolean isExternalIdChanged() { - return this.modifiedParameters.contains("externalId"); - } - - public boolean isDepositAmountChanged() { - return this.modifiedParameters.contains("deposit"); - } - - public boolean isTenureInMonthsChanged() { - return this.modifiedParameters.contains("tenureInMonths"); - } - - public boolean isLockinPeriodChanged() { - return this.modifiedParameters.contains("lockinPeriod"); - } - - public boolean isMaturityActualInterestRateChanged() { - return this.modifiedParameters.contains("maturityInterestRate"); - } - - public boolean isPreClosureInterestRateChanged() { - return this.modifiedParameters.contains("preClosureInterestRate"); - } - - public boolean isCompoundingInterestEveryChanged() { - return this.modifiedParameters.contains("interestCompoundedEvery"); - } - - public boolean isInterestCompoundedEveryPeriodTypeChaged() { - return this.modifiedParameters.contains("interestCompoundedEveryPeriodType"); - } - - public boolean isRenewalAllowedChanged() { - return this.modifiedParameters.contains("renewalAllowed"); - } - - public boolean isPreClosureAllowedChanged() { - return this.modifiedParameters.contains("preClosureAllowed"); - } - - public boolean isInterestWithdrawableChanged() { - return this.modifiedParameters.contains("isInterestWithdrawable"); - } - - public boolean isInterestCompoundingAllowedChanged() { - return this.modifiedParameters.contains("interestCompoundingAllowed"); - } - - public boolean isCommencementDateChanged() { - return this.modifiedParameters.contains("commencementDate"); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommandValidator.java deleted file mode 100644 index ca3a52828..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountCommandValidator.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; - -public class DepositAccountCommandValidator { - - private final DepositAccountCommand command; - - public DepositAccountCommandValidator(final DepositAccountCommand command) { - this.command = command; - } - - public void validateForUpdate() { - - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - - baseDataValidator.reset().parameter("id").value(command.getId()).notNull(); - baseDataValidator.reset().parameter("clientId").value(command.getClientId()).ignoreIfNull().notNull(); - baseDataValidator.reset().parameter("productId").value(command.getProductId()).ignoreIfNull().notNull(); - baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100); - - baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull().notNull() - .zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().notNull() - .integerGreaterThanZero(); - - baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull() - .integerGreaterThanZero(); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()) - .ignoreIfNull().inMinMaxRange(2, 2); - baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).ignoreIfNull(); - - if (command.isNoFieldChanged()) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append("deposit.account").append( - ".no.parameters.for.update"); - StringBuilder defaultEnglishMessage = new StringBuilder("No parameters passed for update."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - "id"); - dataValidationErrors.add(error); - } - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - - public void validateForCreate() { - - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - - baseDataValidator.reset().parameter("clientId").value(command.getClientId()).notNull(); - baseDataValidator.reset().parameter("productId").value(command.getProductId()).notNull(); - baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100); - - baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull() - .zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).ignoreIfNull() - .zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().integerGreaterThanZero(); - - baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull() - .integerGreaterThanZero(); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()) - .ignoreIfNull().inMinMaxRange(2, 2); - baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).notNull(); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawInterestCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawInterestCommand.java deleted file mode 100644 index 2cea06829..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawInterestCommand.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.math.BigDecimal; - -public class DepositAccountWithdrawInterestCommand { - - private final Long accountId; - private final BigDecimal withdrawInterest; - private final String note; - - public DepositAccountWithdrawInterestCommand(final Long accountId, BigDecimal withdrawInterest, String note) { - this.accountId = accountId; - this.withdrawInterest = withdrawInterest; - this.note = note; - } - - public Long getAccountId() { - return accountId; - } - - public BigDecimal getWithdrawInterest() { - return withdrawInterest; - } - - public String getNote() { - return note; - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommand.java deleted file mode 100644 index f4c5bcce5..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommand.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import org.joda.time.LocalDate; - -public class DepositAccountWithdrawalCommand { - - private final Long accountId; - private final String note; - private final LocalDate maturesOnDate; - - public DepositAccountWithdrawalCommand(final Long accountId, final String note, final LocalDate maturesOnDate) { - this.accountId = accountId; - this.note = note; - this.maturesOnDate = maturesOnDate; - } - - public Long getAccountId() { - return accountId; - } - - public String getNote() { - return note; - } - - public LocalDate getMaturesOnDate() { - return maturesOnDate; - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommandValidator.java deleted file mode 100644 index 55a98e3d6..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositAccountWithdrawalCommandValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; - -public class DepositAccountWithdrawalCommandValidator { - - private final DepositAccountWithdrawalCommand command; - - public DepositAccountWithdrawalCommandValidator(final DepositAccountWithdrawalCommand command) { - this.command = command; - } - - public void validate() { - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transaction"); - - baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter("note").value(command.getNote()).notNull(); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommand.java deleted file mode 100644 index d7c9f7267..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommand.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.math.BigDecimal; - -import org.joda.time.LocalDate; - -public class DepositStateTransitionApprovalCommand { - - private final Long accountId; - private final Long productId; - private final LocalDate eventDate; - private final BigDecimal depositAmount; - private final BigDecimal maturityInterestRate; - private final Integer tenureInMonths; - private final Integer interestCompoundedEveryPeriodType; - private final Integer interestCompoundedEvery; - - private final String note; - - public DepositStateTransitionApprovalCommand(final Long resourceIdentifier, final Long productId, final LocalDate eventDate, - final Integer tenureInMonths, final BigDecimal depositAmount, final Integer interestCompoundedEveryPeriodType, - final Integer interestCompoundedEvery, final String note, final BigDecimal maturityInterestRate) { - - this.accountId = resourceIdentifier; - this.eventDate = eventDate; - this.depositAmount = depositAmount; - this.maturityInterestRate = maturityInterestRate; - this.tenureInMonths = tenureInMonths; - this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType; - this.productId = productId; - this.interestCompoundedEvery = interestCompoundedEvery; - - this.note = note; - - } - - public Long getAccountId() { - return accountId; - } - - public LocalDate getEventDate() { - return eventDate; - } - - public BigDecimal getDepositAmount() { - return depositAmount; - } - - public BigDecimal getMaturityInterestRate() { - return maturityInterestRate; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public Integer getInterestCompoundedEveryPeriodType() { - return interestCompoundedEveryPeriodType; - } - - public Long getProductId() { - return productId; - } - - public Integer getInterestCompoundedEvery() { - return interestCompoundedEvery; - } - - public String getNote() { - return note; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommandValidator.java deleted file mode 100644 index 01b45d4e1..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionApprovalCommandValidator.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; - -public class DepositStateTransitionApprovalCommandValidator { - - private final DepositStateTransitionApprovalCommand command; - - public DepositStateTransitionApprovalCommandValidator(final DepositStateTransitionApprovalCommand command) { - this.command = command; - } - - public void validate() { - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transition"); - baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter("commencementDate").value(command.getEventDate()).notNull(); - - baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull() - .zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()) - .ignoreIfNull().inMinMaxRange(2, 2); - - baseDataValidator.reset().parameter("note").value(command.getNote()).notNull(); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionCommand.java deleted file mode 100644 index e32f2aa20..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/DepositStateTransitionCommand.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import org.joda.time.LocalDate; - -public class DepositStateTransitionCommand { - - private final Long accountId; - private final LocalDate eventDate; - - private final String note; - - public DepositStateTransitionCommand(final Long accountId, final LocalDate enentDate, final String note) { - this.accountId = accountId; - this.eventDate = enentDate; - this.note = note; - } - - public Long getAccountId() { - return accountId; - } - - public LocalDate getEventDate() { - return eventDate; - } - - public String getNote() { - return note; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/WithDrawDepositAccountInterestCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/WithDrawDepositAccountInterestCommandValidator.java deleted file mode 100644 index e13c26c8d..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/command/WithDrawDepositAccountInterestCommandValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.command; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; - -public class WithDrawDepositAccountInterestCommandValidator { - - private final DepositAccountWithdrawInterestCommand command; - - public WithDrawDepositAccountInterestCommandValidator(final DepositAccountWithdrawInterestCommand command) { - this.command = command; - } - - public void validate() { - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transaction"); - - baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter("amount").value(command.getWithdrawInterest()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("note").value(command.getNote()).notNull(); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountData.java deleted file mode 100644 index bd3f99949..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountData.java +++ /dev/null @@ -1,650 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.data; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.joda.time.Days; -import org.joda.time.LocalDate; -import org.joda.time.Months; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductLookup; - -/** - * Immutable data object for deposit accounts. - */ -public class DepositAccountData { - - private final Long id; - private final String externalId; - private final EnumOptionData status; - private final Long clientId; - private final String clientName; - private final Long productId; - private final String productName; - - private final CurrencyData currency; - private final BigDecimal deposit; - private final BigDecimal maturityInterestRate; - - private final Integer tenureInMonths; - private final LocalDate projectedCommencementDate; - private final LocalDate actualCommencementDate; - private final LocalDate maturedOn; - private final LocalDate withdrawnonDate; - private final LocalDate rejectedonDate; - private final LocalDate closedonDate; - private final BigDecimal projectedInterestAccrued; - private final BigDecimal actualInterestAccrued; - private final BigDecimal projectedMaturityAmount; - private final BigDecimal actualMaturityAmount; - - private final Integer interestCompoundedEvery; - private final EnumOptionData interestCompoundedEveryPeriodType; - private final boolean renewalAllowed; - private final boolean preClosureAllowed; - private final BigDecimal preClosureInterestRate; - - private final boolean isInterestWithdrawable; - private final BigDecimal interestPaid; - private final boolean interestCompoundingAllowed; - - private final List interestCompoundedEveryPeriodTypeOptions; - private final List productOptions; - - private final Collection transactions; - private final DepositPermissionData permissions; - private final BigDecimal availableInterestForWithdrawal; - private final BigDecimal availableWithdrawalAmount; - private final LocalDate todaysDate; - - private final boolean isLockinPeriodAllowed; - private final Integer lockinPeriod; - private final EnumOptionData lockinPeriodType; - - private final BigDecimal availableInterest; - private final BigDecimal interestPostedAmount; - private final LocalDate lastInterestPostedDate; - private final LocalDate nextInterestPostedDate; - - private final String imageKey; - private String printFDdetailsLocation; - private final String fatherName; - private final String address; - - /* - * used when returning account template data but only a clientId is passed, - * no selected product. - */ - public static DepositAccountData createFrom(final Long clientId, final String clientDisplayName) { - return new DepositAccountData(clientId, clientDisplayName); - } - - private DepositAccountData(final Long clientId, final String clientName) { - this.id = null; - this.externalId = null; - this.status = null; - this.clientId = clientId; - this.clientName = clientName; - this.productId = null; - this.productName = null; - this.currency = null; - this.deposit = null; - this.maturityInterestRate = null; - this.tenureInMonths = null; - this.projectedCommencementDate = null; - this.actualCommencementDate = null; - this.maturedOn = null; - this.projectedInterestAccrued = null; - this.actualInterestAccrued = null; - this.projectedMaturityAmount = null; - this.actualMaturityAmount = null; - this.interestCompoundedEvery = null; - this.interestCompoundedEveryPeriodType = null; - this.renewalAllowed = false; - this.preClosureAllowed = false; - this.preClosureInterestRate = null; - - this.interestCompoundedEveryPeriodTypeOptions = new ArrayList(); - this.productOptions = null; - - this.withdrawnonDate = null; - this.closedonDate = null; - this.rejectedonDate = null; - - this.transactions = null; - this.permissions = null; - - this.interestPaid = null; - this.isInterestWithdrawable = false; - this.interestCompoundingAllowed = false; - this.availableInterestForWithdrawal = null; - this.availableWithdrawalAmount = null; - this.todaysDate = null; - - this.isLockinPeriodAllowed = false; - this.lockinPeriod = null; - this.lockinPeriodType = null; - - this.availableInterest = null; - this.interestPostedAmount = null; - this.lastInterestPostedDate = null; - this.nextInterestPostedDate = null; - - this.imageKey = null; - this.printFDdetailsLocation = null; - this.fatherName = null; - this.address = null; - - } - - public DepositAccountData(final DepositAccountData account, final List interestCompoundedEveryPeriodTypeOptions, - final Collection productOptions) { - this.id = account.getId(); - this.externalId = account.getExternalId(); - this.status = account.getStatus(); - this.clientId = account.getClientId(); - this.clientName = account.getClientName(); - this.productId = account.getProductId(); - this.productName = account.getProductName(); - this.currency = account.getCurrency(); - this.deposit = account.getDeposit(); - this.maturityInterestRate = account.getMaturityInterestRate(); - this.tenureInMonths = account.getTenureInMonths(); - this.projectedCommencementDate = account.getProjectedCommencementDate(); - this.actualCommencementDate = account.getActualCommencementDate(); - this.maturedOn = account.getMaturedOn(); - this.projectedInterestAccrued = account.getProjectedInterestAccrued(); - this.actualInterestAccrued = account.getActualInterestAccrued(); - this.projectedMaturityAmount = account.getProjectedMaturityAmount(); - this.actualMaturityAmount = account.getActualMaturityAmount(); - this.interestCompoundedEvery = account.getInterestCompoundedEvery(); - this.interestCompoundedEveryPeriodType = account.getInterestCompoundedEveryPeriodType(); - this.renewalAllowed = account.isRenewalAllowed(); - this.preClosureAllowed = account.isPreClosureAllowed(); - this.preClosureInterestRate = account.getPreClosureInterestRate(); - - this.interestCompoundedEveryPeriodTypeOptions = interestCompoundedEveryPeriodTypeOptions; - this.productOptions = defaultIfEmpty(productOptions); - - this.withdrawnonDate = account.getWithdrawnonDate(); - this.rejectedonDate = account.getRejectedonDate(); - this.closedonDate = account.getClosedonDate(); - - this.transactions = account.getTransactions(); - this.permissions = account.getPermissions(); - this.interestPaid = account.getInterestPaid(); - this.isInterestWithdrawable = account.isInterestWithdrawable(); - this.interestCompoundingAllowed = account.isInterestCompoundingAllowed(); - this.availableInterestForWithdrawal = determineAvailableInterestForWithdrawal(account); - this.availableWithdrawalAmount = determineAvalableWithdrawalAmount(account); - this.todaysDate = new LocalDate(); - - this.lockinPeriod = account.getLockinPeriod(); - this.lockinPeriodType = account.getLockinPeriodType(); - this.isLockinPeriodAllowed = account.isLockinPeriodAllowed(); - - this.availableInterest = account.getAvailableInterest(); - this.interestPostedAmount = account.getInterestPostedAmount(); - this.lastInterestPostedDate = account.getLastInterestPostedDate(); - this.nextInterestPostedDate = account.getNextInterestPostedDate(); - - this.imageKey = account.getImageKey(); - this.printFDdetailsLocation = account.getPrintFDdetailsLocation(); - this.fatherName=account.getFatherName(); - this.address=account.getAddress(); - } - - public DepositAccountData(final DepositAccountData account, final DepositPermissionData permissions, - final Collection transactions) { - this.id = account.getId(); - this.externalId = account.getExternalId(); - this.status = account.getStatus(); - this.clientId = account.getClientId(); - this.clientName = account.getClientName(); - this.productId = account.getProductId(); - this.productName = account.getProductName(); - this.currency = account.getCurrency(); - this.deposit = account.getDeposit(); - this.maturityInterestRate = account.getMaturityInterestRate(); - this.tenureInMonths = account.getTenureInMonths(); - this.projectedCommencementDate = account.getProjectedCommencementDate(); - this.actualCommencementDate = account.getActualCommencementDate(); - this.maturedOn = account.getMaturedOn(); - this.projectedInterestAccrued = account.getProjectedInterestAccrued(); - this.actualInterestAccrued = account.getActualInterestAccrued(); - this.projectedMaturityAmount = account.getProjectedMaturityAmount(); - this.actualMaturityAmount = account.getActualMaturityAmount(); - this.interestCompoundedEvery = account.getInterestCompoundedEvery(); - this.interestCompoundedEveryPeriodType = account.getInterestCompoundedEveryPeriodType(); - this.renewalAllowed = account.isRenewalAllowed(); - this.preClosureAllowed = account.isPreClosureAllowed(); - this.preClosureInterestRate = account.getPreClosureInterestRate(); - - this.interestCompoundedEveryPeriodTypeOptions = account.getInterestCompoundedEveryPeriodTypeOptions(); - this.productOptions = account.getProductOptions(); - - this.withdrawnonDate = account.getWithdrawnonDate(); - this.rejectedonDate = account.getRejectedonDate(); - this.closedonDate = account.getClosedonDate(); - - this.transactions = transactions; - this.permissions = permissions; - this.interestPaid = account.getInterestPaid(); - this.isInterestWithdrawable = account.isInterestWithdrawable(); - this.interestCompoundingAllowed = account.isInterestCompoundingAllowed(); - this.availableInterestForWithdrawal = determineAvailableInterestForWithdrawal(account); - this.availableWithdrawalAmount = determineAvalableWithdrawalAmount(account); - this.todaysDate = new LocalDate(); - - this.lockinPeriod = account.getLockinPeriod(); - this.lockinPeriodType = account.getLockinPeriodType(); - this.isLockinPeriodAllowed = account.isLockinPeriodAllowed(); - - this.availableInterest = account.getAvailableInterest(); - this.interestPostedAmount = account.getInterestPostedAmount(); - this.lastInterestPostedDate = account.getLastInterestPostedDate(); - this.nextInterestPostedDate = account.getNextInterestPostedDate(); - this.imageKey = account.getImageKey(); - this.printFDdetailsLocation = account.getPrintFDdetailsLocation(); - this.fatherName=account.getFatherName(); - this.address=account.getAddress(); - } - - public DepositAccountData(final Long id, final String externalId, final EnumOptionData status, final Long clientId, - final String clientName, final Long productId, final String productName, final CurrencyData currency, final BigDecimal deposit, - final BigDecimal interestRate, final Integer tenureInMonths, final LocalDate projectedCommencementDate, - final LocalDate actualCommencementDate, final LocalDate maturedOn, final BigDecimal projectedInterestAccrued, - final BigDecimal actualInterestAccrued, final BigDecimal projectedMaturityAmount, final BigDecimal actualMaturityAmount, - final Integer interestCompoundedEvery, final EnumOptionData interestCompoundedEveryPeriodType, final boolean renewalAllowed, - final boolean preClosureAllowed, final BigDecimal preClosureInterestRate, final LocalDate withdrawnonDate, - final LocalDate rejectedonDate, final LocalDate closedonDate, final boolean isInterestWithdrawable, - final BigDecimal interestPaid, final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final EnumOptionData lockinPeriodType, final BigDecimal availableInterest, - final BigDecimal interestPostedAmount, final LocalDate lastInterestPostedDate, final LocalDate nextInterestPostedDate, - final String fatherName, final String address, final String imageKey) { - this.id = id; - this.externalId = externalId; - this.status = status; - this.clientId = clientId; - this.clientName = clientName; - this.productId = productId; - this.productName = productName; - this.currency = currency; - this.deposit = deposit; - this.maturityInterestRate = interestRate; - this.tenureInMonths = tenureInMonths; - this.projectedCommencementDate = projectedCommencementDate; - this.actualCommencementDate = actualCommencementDate; - this.maturedOn = maturedOn; - this.projectedInterestAccrued = projectedInterestAccrued; - this.actualInterestAccrued = actualInterestAccrued; - this.projectedMaturityAmount = projectedMaturityAmount; - this.actualMaturityAmount = actualMaturityAmount; - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType; - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - this.preClosureInterestRate = preClosureInterestRate; - - this.interestCompoundedEveryPeriodTypeOptions = new ArrayList(); - this.productOptions = new ArrayList(); - - this.withdrawnonDate = withdrawnonDate; - this.rejectedonDate = rejectedonDate; - this.closedonDate = closedonDate; - - this.transactions = null; - this.permissions = null; - - this.interestPaid = interestPaid; - this.isInterestWithdrawable = isInterestWithdrawable; - this.interestCompoundingAllowed = interestCompoundingAllowed; - this.availableInterestForWithdrawal = BigDecimal.ZERO; - this.availableWithdrawalAmount = BigDecimal.ZERO; - this.todaysDate = new LocalDate(); - - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - - this.availableInterest = availableInterest; - this.interestPostedAmount = interestPostedAmount; - this.lastInterestPostedDate = lastInterestPostedDate; - this.nextInterestPostedDate = nextInterestPostedDate; - - this.imageKey = imageKey; - this.fatherName = fatherName; - this.address = address; - this.printFDdetailsLocation = null; - } - - public DepositAccountData(final Long clientId, final String clientName, final Long productId, final String productName, - final CurrencyData currency, final BigDecimal deposit, final BigDecimal interestRate, final Integer tenureInMonths, - final Integer interestCompoundedEvery, final EnumOptionData interestCompoundedEveryPeriodType, final boolean renewalAllowed, - final boolean preClosureAllowed, final BigDecimal preClosureInterestRate, final boolean interestCompoundingAllowed, Integer lockinPeriod, - EnumOptionData lockinPeriodType, boolean lockinPeriodAllowed) { - this.id = null; - this.externalId = null; - this.status = null; - this.clientId = clientId; - this.clientName = clientName; - this.productId = productId; - this.productName = productName; - this.currency = currency; - this.deposit = deposit; - this.maturityInterestRate = interestRate; - this.tenureInMonths = tenureInMonths; - this.projectedCommencementDate = new LocalDate(); - this.actualCommencementDate = null; - this.maturedOn = null; - this.projectedInterestAccrued = null; - this.actualInterestAccrued = null; - this.projectedMaturityAmount = null; - this.actualMaturityAmount = null; - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType; - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - this.preClosureInterestRate = preClosureInterestRate; - - this.interestCompoundedEveryPeriodTypeOptions = new ArrayList(); - this.productOptions = new ArrayList(); - - this.withdrawnonDate = null; - this.closedonDate = null; - this.rejectedonDate = null; - - this.transactions = null; - this.permissions = null; - this.interestPaid = null; - this.isInterestWithdrawable = false; - this.interestCompoundingAllowed = interestCompoundingAllowed; - this.availableInterestForWithdrawal = BigDecimal.ZERO; - this.availableWithdrawalAmount = BigDecimal.ZERO; - this.todaysDate = null; - - this.lockinPeriod = lockinPeriod; - this.isLockinPeriodAllowed = lockinPeriodAllowed; - this.lockinPeriodType = lockinPeriodType; - - this.availableInterest = BigDecimal.ZERO; - this.interestPostedAmount = BigDecimal.ZERO; - this.lastInterestPostedDate = null; - this.nextInterestPostedDate = null; - - this.imageKey = null; - this.printFDdetailsLocation = null; - this.fatherName=null; - this.address=null; - } - - public Long getId() { - return id; - } - - public String getExternalId() { - return externalId; - } - - public EnumOptionData getStatus() { - return status; - } - - public Long getClientId() { - return clientId; - } - - public String getClientName() { - return clientName; - } - - public Long getProductId() { - return productId; - } - - public String getProductName() { - return productName; - } - - public CurrencyData getCurrency() { - return currency; - } - - public BigDecimal getDeposit() { - return deposit; - } - - public BigDecimal getMaturityInterestRate() { - return maturityInterestRate; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public LocalDate getProjectedCommencementDate() { - return projectedCommencementDate; - } - - public LocalDate getActualCommencementDate() { - return actualCommencementDate; - } - - public LocalDate getMaturedOn() { - return maturedOn; - } - - public BigDecimal getProjectedInterestAccrued() { - return projectedInterestAccrued; - } - - public BigDecimal getActualInterestAccrued() { - return actualInterestAccrued; - } - - public BigDecimal getProjectedMaturityAmount() { - return projectedMaturityAmount; - } - - public BigDecimal getActualMaturityAmount() { - return actualMaturityAmount; - } - - public Integer getInterestCompoundedEvery() { - return interestCompoundedEvery; - } - - public EnumOptionData getInterestCompoundedEveryPeriodType() { - return interestCompoundedEveryPeriodType; - } - - public boolean isRenewalAllowed() { - return renewalAllowed; - } - - public boolean isPreClosureAllowed() { - return preClosureAllowed; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public List getInterestCompoundedEveryPeriodTypeOptions() { - return interestCompoundedEveryPeriodTypeOptions; - } - - public List getProductOptions() { - return productOptions; - } - - public LocalDate getWithdrawnonDate() { - return withdrawnonDate; - } - - public LocalDate getRejectedonDate() { - return rejectedonDate; - } - - public LocalDate getClosedonDate() { - return closedonDate; - } - - public Collection getTransactions() { - return transactions; - } - - public DepositPermissionData getPermissions() { - return permissions; - } - - public boolean isInterestWithdrawable() { - return isInterestWithdrawable; - } - - public BigDecimal getInterestPaid() { - return interestPaid; - } - - public boolean isInterestCompoundingAllowed() { - return interestCompoundingAllowed; - } - - public BigDecimal getAvailableInterestForWithdrawal() { - return availableInterestForWithdrawal; - } - - public BigDecimal getAvailableWithdrawalAmount() { - return availableWithdrawalAmount; - } - - public LocalDate getTodaysDate() { - return todaysDate; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public EnumOptionData getLockinPeriodType() { - return lockinPeriodType; - } - - public BigDecimal getAvailableInterest() { - return this.availableInterest; - } - - public BigDecimal getInterestPostedAmount() { - return this.interestPostedAmount; - } - - public LocalDate getLastInterestPostedDate() { - return this.lastInterestPostedDate; - } - - public LocalDate getNextInterestPostedDate() { - return this.nextInterestPostedDate; - } - - public String getPrintFDdetailsLocation() { - return this.printFDdetailsLocation; - } - - public void setPrintFDdetailsLocation(String printFDdetailsLocation) { - this.printFDdetailsLocation = printFDdetailsLocation; - } - - public String getImageKey() { - return this.imageKey; - } - - public String getFatherName() { - return this.fatherName; - } - - public String getAddress() { - return this.address; - } - - private BigDecimal determineAvailableInterestForWithdrawal(final DepositAccountData account) { - BigDecimal availableInterestForWithdrawal = BigDecimal.ZERO; - - if (this.status != null) { - if (account.getStatus().getId() == 300) { - BigDecimal interestGettingForPeriod = BigDecimal.valueOf(account.getActualInterestAccrued().doubleValue() - / new Double(account.getTenureInMonths())); - LocalDate interestWithdrawingDate = new LocalDate().isBefore(getMaturedOn()) ? new LocalDate() : getMaturedOn().plusDays(1); - Integer noOfMonthsforInterestCal = Months.monthsBetween(account.getActualCommencementDate(), interestWithdrawingDate) - .getMonths(); - Integer noOfPeriods = noOfMonthsforInterestCal / account.getInterestCompoundedEvery(); - - availableInterestForWithdrawal = BigDecimal.valueOf(interestGettingForPeriod.multiply(new BigDecimal(noOfPeriods)) - .doubleValue() - account.getInterestPaid().doubleValue()); - } else { - return BigDecimal.ZERO; - } - } else - return null; - - return availableInterestForWithdrawal; - } - - private BigDecimal determineAvalableWithdrawalAmount(final DepositAccountData account) { - - BigDecimal avalablePreclosureWithdrawalAmount = null; - if (this.status != null) { - if (account.getStatus().getId() == 300) { - // if(new LocalDate().isBefore(account.getMaturedOn()) || new - // LocalDate().isEqual(account.getMaturedOn())){ - Integer days = Days.daysBetween(account.getLastInterestPostedDate(), new LocalDate()).getDays(); - avalablePreclosureWithdrawalAmount = account.getAvailableInterest().add(account.getDeposit()) - .add(determineRemainInerestAmount(account.getDeposit(), account.getPreClosureInterestRate(), days)); - - // }else if(new LocalDate().isAfter(account.getMaturedOn())){ - // Integer days = - // Days.daysBetween(account.getLastInterestPostedDate(), new - // LocalDate()).getDays(); - // avalablePreclosureWithdrawalAmount=account.getAvailableInterest().add(account.getDeposit()).add(determineRemainInerestAmount(account.getDeposit(), - // account.getPreClosureInterestRate(), days)); - // } - } else { - avalablePreclosureWithdrawalAmount = account.getDeposit(); - } - } - return avalablePreclosureWithdrawalAmount; - } - - private BigDecimal determineRemainInerestAmount(final BigDecimal depsoitAmount, final BigDecimal interstRateApplicable, - final Integer days) { - - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - Integer daysInYear = 365; - BigDecimal interestRateAsFraction = interstRateApplicable.divide(BigDecimal.valueOf(100), mc); - BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc); - return BigDecimal.valueOf(depsoitAmount.doubleValue() * days.doubleValue() * interestRateForOneDay.doubleValue()); - - } - - private List defaultIfEmpty(final Collection collection) { - List returnCollection = null; - if (collection != null && !collection.isEmpty()) { - returnCollection = new ArrayList(collection); - } - return returnCollection; - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountTransactionData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountTransactionData.java deleted file mode 100644 index de61f311a..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountTransactionData.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.data; - -import java.math.BigDecimal; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; - -/** - * Immutable data object to represent transactions on a deposit account. - */ -public class DepositAccountTransactionData { - - private final Long transactionId; - private final EnumOptionData transactionType; - private final LocalDate transactionDate; - private final BigDecimal transactionAmount; - private final Long accountId; - private final BigDecimal interestAmount; - private final BigDecimal total; - - public DepositAccountTransactionData(final Long transactionId, final Long accountId, final EnumOptionData transactionType, - final LocalDate transactionDate, final BigDecimal transactionAmount, final BigDecimal interstAmount, final BigDecimal total) { - this.transactionId = transactionId; - this.accountId = accountId; - this.transactionType = transactionType; - this.transactionDate = transactionDate; - this.transactionAmount = transactionAmount; - this.interestAmount = interstAmount; - this.total = total; - } - - public Long getAccountId() { - return accountId; - } - - public Long getTransactionId() { - return transactionId; - } - - public EnumOptionData getTransactionType() { - return transactionType; - } - - public LocalDate getTransactionDate() { - return transactionDate; - } - - public BigDecimal getTransactionAmount() { - return transactionAmount; - } - - public BigDecimal getInterestAmount() { - return interestAmount; - } - - public BigDecimal getTotal() { - return total; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountsForLookup.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountsForLookup.java deleted file mode 100644 index 3f54109ac..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositAccountsForLookup.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.data; - -public class DepositAccountsForLookup { - - private final Long id; - - public DepositAccountsForLookup(final Long id) { - this.id = id; - } - - public Long getId() { - return id; - } - -} - diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositPermissionData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositPermissionData.java deleted file mode 100644 index 48d72abaa..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/data/DepositPermissionData.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.data; - -public class DepositPermissionData { - - private final boolean rejectAllowed; - private final boolean withdrawnByApplicantAllowed; - private final boolean undoApprovalAllowed; - private final boolean pendingApproval; - private final boolean isInterestWithdrawalAllowed; - private final boolean renewelAllowed; - private final boolean isMaturedDepositAccount; - - private final boolean anyActionOnAccountAllowed; - - 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 boolean isRejectAllowed() { - return rejectAllowed; - } - - public boolean isWithdrawnByApplicantAllowed() { - return withdrawnByApplicantAllowed; - } - - public boolean isUndoApprovalAllowed() { - return undoApprovalAllowed; - } - - public boolean isPendingApproval() { - return pendingApproval; - } - - public boolean isAnyActionOnAccountAllowed() { - return anyActionOnAccountAllowed; - } - - public boolean isInterestWithdrawalAllowed() { - return isInterestWithdrawalAllowed; - } - - public boolean isRenewelAllowed() { - return renewelAllowed; - } - - public boolean isMaturedDepositAccount() { - return isMaturedDepositAccount; - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccount.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccount.java deleted file mode 100644 index 4b1516dcd..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccount.java +++ /dev/null @@ -1,873 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.OrderBy; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.UniqueConstraint; - -import org.apache.commons.lang.StringUtils; -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; -import org.joda.time.Days; -import org.joda.time.LocalDate; -import org.joda.time.Months; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.client.domain.Client; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.InvalidDepositStateTransitionException; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.DepositProduct; -import org.mifosplatform.useradministration.domain.AppUser; - -@Entity -@Table(name = "m_deposit_account", uniqueConstraints = @UniqueConstraint(name = "deposit_acc_external_id", columnNames = { "external_id" })) -public class DepositAccount extends AbstractAuditableCustom { - - @ManyToOne - @JoinColumn(name = "client_id", nullable = false) - private Client client; - - @ManyToOne - @JoinColumn(name = "product_id") - private DepositProduct product; - - @Column(name = "external_id") - private String externalId; - - @Embedded - private MonetaryCurrency currency; - - @Column(name = "deposit_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal depositAmount; - - @Column(name = "maturity_nominal_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal interestRate; - - @Column(name = "tenure_months", nullable = false) - private Integer tenureInMonths; - - @Column(name = "interest_compounded_every", nullable = false) - private Integer interestCompoundedEvery; - - @Column(name = "interest_compounded_every_period_enum", nullable = false) - private Integer interestCompoundedFrequencyType; - - @Temporal(TemporalType.DATE) - @Column(name = "projected_commencement_date") - private Date projectedCommencementDate; - - @Temporal(TemporalType.DATE) - @Column(name = "actual_commencement_date") - private Date actualCommencementDate; - - @Temporal(TemporalType.DATE) - @Column(name = "matures_on_date") - private Date maturesOnDate; - - @Column(name = "projected_interest_accrued_on_maturity", scale = 6, precision = 19, nullable = false) - private BigDecimal projectedInterestAccruedOnMaturity; - - @Column(name = "actual_interest_accrued", scale = 6, precision = 19, nullable = false) - private BigDecimal interestAccrued; - - @Column(name = "projected_total_maturity_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal projectedTotalOnMaturity; - - @Column(name = "actual_total_amount", scale = 6, precision = 19, nullable = false) - private BigDecimal total; - - @Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal preClosureInterestRate; - - @Column(name = "is_renewal_allowed", nullable = false) - private boolean renewalAllowed = false; - - @Column(name = "is_preclosure_allowed", nullable = false) - private boolean preClosureAllowed = false; - - @Column(name = "is_deleted", nullable = false) - private boolean deleted = false; - - @Column(name = "status_enum", nullable = false) - private Integer depositStatus; - - @SuppressWarnings("unused") - @Temporal(TemporalType.DATE) - @Column(name = "closedon_date") - private Date closedOnDate; - - @SuppressWarnings("unused") - @Temporal(TemporalType.DATE) - @Column(name = "rejectedon_date") - private Date rejectedOnDate; - - @SuppressWarnings("unused") - @Temporal(TemporalType.DATE) - @Column(name = "withdrawnon_date") - private Date withdrawnOnDate; - - @Column(name = "interest_paid", scale = 6, precision = 19, nullable = false) - private BigDecimal interstPaid; - - @Column(name = "is_interest_withdrawable", nullable = false) - private boolean isInterestWithdrawable = false; - - @Column(name = "is_compounding_interest_allowed", nullable = false) - private boolean interestCompoundingAllowed = false; - - // see - // http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags - @OrderBy(value = "id") - @LazyCollection(LazyCollectionOption.FALSE) - @OneToMany(cascade = CascadeType.ALL, mappedBy = "depositAccount", orphanRemoval = true) - private final List depositaccountTransactions = new ArrayList(); - - @SuppressWarnings("unused") - @OneToOne(optional = true, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "renewed_account_id") - private DepositAccount renewdAccount; - - @Column(name = "is_lock_in_period_allowed", nullable = false) - private boolean isLockinPeriodAllowed = false; - - @Column(name = "lock_in_period", nullable = false) - private Integer lockinPeriod; - - @Column(name = "lock_in_period_type", nullable = false) - private PeriodFrequencyType lockinPeriodType; - - // for interest posting - @Column(name = "available_interest", scale = 6, precision = 19) - private BigDecimal availableInterest; - - @Column(name = "interest_posted_amount", scale = 6, precision = 19) - private BigDecimal interestPostedAmount; - - @Temporal(TemporalType.DATE) - @Column(name = "last_interest_posted_date") - private Date lastInterestPostedDate; - - @Temporal(TemporalType.DATE) - @Column(name = "next_interest_posting_date") - private Date nextInterestPostingDate; - - public DepositAccount openNew(final Client client, final DepositProduct product, final String externalId, final Money deposit, - final BigDecimal maturityInterestRate, final BigDecimal preClosureInterestRate, final Integer tenureInMonths, - final Integer interestCompoundedEvery, final PeriodFrequencyType interestCompoundedFrequencyPeriodType, - final LocalDate commencementDate, final boolean renewalAllowed, final boolean preClosureAllowed, - final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator, - final DepositLifecycleStateMachine depositLifecycleStateMachine, final boolean isInterstWithdrawable, - final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, - final PeriodFrequencyType lockinPeriodType) { - - Money futureValueOnMaturity = null; - - if (interestCompoundingAllowed) { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityFor(deposit, tenureInMonths, - maturityInterestRate, interestCompoundedEvery); - } else { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityForSimpleInterest(deposit, - tenureInMonths, maturityInterestRate, interestCompoundedEvery); - } - - DepositAccountStatus from = null; - if (depositStatus != null) { - from = DepositAccountStatus.fromInt(depositStatus); - } - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CREATED, from); - depositStatus = statusEnum.getValue(); - - return new DepositAccount(client, product, externalId, deposit, maturityInterestRate, preClosureInterestRate, tenureInMonths, - interestCompoundedEvery, interestCompoundedFrequencyPeriodType, commencementDate, renewalAllowed, preClosureAllowed, - futureValueOnMaturity, depositStatus, isInterstWithdrawable, interestCompoundingAllowed, isLockinPeriodAllowed, - lockinPeriod, lockinPeriodType); - } - - public DepositAccount() { - this.product = null; - } - - public DepositAccount(final Client client, final DepositProduct product, final String externalId, final Money deposit, - final BigDecimal interestRate, final BigDecimal preClosureInterestRate, final Integer termInMonths, - final Integer interestCompoundedEvery, final PeriodFrequencyType interestCompoundedFrequencyPeriodType, - final LocalDate commencementDate, final boolean renewalAllowed, final boolean preClosureAllowed, - final Money futureValueOnMaturity, final Integer depositStatus, final boolean isInterestWithdrawable, - final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed, final Integer lockinPeriod, - final PeriodFrequencyType lockinPeriodType) { - this.client = client; - this.product = product; - setExternalId(externalId); - - this.currency = deposit.getCurrency(); - this.depositAmount = deposit.getAmount(); - product.validateDepositInRange(this.depositAmount); - this.interestRate = interestRate; - product.validateInterestRateInRange(interestRate); - this.tenureInMonths = termInMonths; - - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedFrequencyType = interestCompoundedFrequencyPeriodType.getValue(); - if (commencementDate != null) { - this.projectedCommencementDate = commencementDate.toDate(); - this.maturesOnDate = commencementDate.plusMonths(this.tenureInMonths).minusDays(1).toDate(); - } - - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - - this.preClosureInterestRate = preClosureInterestRate; - this.isInterestWithdrawable = isInterestWithdrawable; - this.interestCompoundingAllowed = interestCompoundingAllowed; - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - - // derived fields - this.projectedInterestAccruedOnMaturity = futureValueOnMaturity.minus(deposit).getAmount(); - this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount(); - this.depositStatus = depositStatus; - this.interestAccrued = BigDecimal.ZERO; - this.interstPaid = BigDecimal.ZERO; - this.total = BigDecimal.ZERO; - } - - private void setExternalId(final String externalId) { - if (StringUtils.isNotBlank(externalId)) { - this.externalId = externalId.trim(); - } else { - this.externalId = null; - } - } - - public boolean isDeleted() { - return deleted; - } - - /** - * Delete is a soft delete. Updates flag on account so it wont appear - * in query/report results. - * - * Any fields with unique constraints and prepended with id of record. - */ - public void delete() { - this.deleted = true; - this.externalId = this.getId() + "_" + this.externalId; - } - - public Map approve(final LocalDate actualCommencementDate, - final DepositLifecycleStateMachine depositLifecycleStateMachine, final JsonCommand command, - final FixedTermDepositInterestCalculator calculator) { - - final Map actualChanges = new LinkedHashMap(20); - final String localeAsInput = command.locale(); - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_APPROVED, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnum.getValue(); - - final String tenureInMonthsParamName = "tenureInMonths"; - if (command.isChangeInIntegerParameterNamed(tenureInMonthsParamName, this.tenureInMonths)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureInMonthsParamName); - actualChanges.put(tenureInMonthsParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.tenureInMonths = newValue; - } - - final String maturityInterestRateParamName = "maturityInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(maturityInterestRateParamName, this.interestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(maturityInterestRateParamName); - actualChanges.put(maturityInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestRate = newValue; - } - this.product.validateInterestRateInRange(this.interestRate); - - final String depositParamName = "deposit"; - if (command.isChangeInBigDecimalParameterNamed(depositParamName, this.depositAmount)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(depositParamName); - actualChanges.put(depositParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.depositAmount = newValue; - } - this.product.validateDepositInRange(this.depositAmount); - - final String interestCompoundedEveryParamName = "interestCompoundedEvery"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryParamName, this.interestCompoundedEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryParamName); - actualChanges.put(interestCompoundedEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestCompoundedEvery = newValue; - } - - final String interestCompoundedEveryPeriodTypeParamName = "interestCompoundedEveryPeriodType"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryPeriodTypeParamName, this.interestCompoundedFrequencyType)) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryPeriodTypeParamName); - actualChanges.put(interestCompoundedEveryPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestCompoundedFrequencyType = PeriodFrequencyType.fromInt(newValue).getValue(); - } - - this.actualCommencementDate = actualCommencementDate.toDate(); - this.maturesOnDate = getActualCommencementDate().plusMonths(this.tenureInMonths).minusDays(1).toDate(); - - Money futureValueOnMaturity = null; - - if (this.interestCompoundingAllowed) { - futureValueOnMaturity = calculator.calculateInterestOnMaturityFor(getDeposit(), this.tenureInMonths, this.interestRate, - this.interestCompoundedEvery); - } else { - futureValueOnMaturity = calculator.calculateInterestOnMaturityForSimpleInterest(getDeposit(), this.tenureInMonths, - this.interestRate, this.interestCompoundedEvery); - } - this.interestAccrued = futureValueOnMaturity.minus(getDeposit()).getAmount(); - this.total = futureValueOnMaturity.getAmount(); - - DepositAccountTransaction depositaccountTransaction = DepositAccountTransaction.deposit(getDeposit(), getActualCommencementDate(), - null); - depositaccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositaccountTransaction); - - // for interest posting initializing - this.lastInterestPostedDate = this.actualCommencementDate; - this.nextInterestPostingDate = new LocalDate(this.lastInterestPostedDate).plusMonths(this.interestCompoundedEvery).toDate(); - this.availableInterest = BigDecimal.ZERO; - this.interestPostedAmount = BigDecimal.ZERO; - - LocalDate submittalDate = new LocalDate(this.projectedCommencementDate); - if (actualCommencementDate.isBefore(submittalDate)) { - final String errorMessage = "The date on which a deposit is approved cannot be before its submittal date: " - + submittalDate.toString(); - throw new InvalidDepositStateTransitionException("approval", "cannot.be.before.submittal.date", errorMessage, - getActualCommencementDate(), submittalDate); - } - - if (actualCommencementDate.isAfter(new LocalDate())) { - final String errorMessage = "The date on which a deposit is approved cannot be in the future."; - throw new InvalidDepositStateTransitionException("approval", "cannot.be.a.future.date", errorMessage, - getActualCommencementDate()); - } - return actualChanges; - } - - public LocalDate getActualCommencementDate() { - LocalDate date = null; - if (this.actualCommencementDate != null) { - date = new LocalDate(this.actualCommencementDate); - } - return date; - } - - public LocalDate getProjectedCommencementDate() { - LocalDate date = null; - if (this.projectedCommencementDate != null) { - date = new LocalDate(this.projectedCommencementDate); - } - return date; - } - - public LocalDate getMaturityDate() { - LocalDate date = null; - if (this.maturesOnDate != null) { - date = new LocalDate(this.maturesOnDate); - } - return date; - } - - public List getDepositaccountTransactions() { - return depositaccountTransactions; - } - - public BigDecimal getProjectedTotalOnMaturity() { - return projectedTotalOnMaturity; - } - - public BigDecimal getTotal() { - return total; - } - - public boolean isInterestCompoundingAllowed() { - return interestCompoundingAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public PeriodFrequencyType getLockinPeriodType() { - return lockinPeriodType; - } - - public void reject(final LocalDate rejectedOn, final DepositLifecycleStateMachine depositLifecycleStateMachine) { - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_REJECTED, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnum.getValue(); - - this.maturesOnDate = null; - this.rejectedOnDate = rejectedOn.toDateTimeAtCurrentTime().toDate(); - this.closedOnDate = rejectedOn.toDateTimeAtCurrentTime().toDate(); - - if (rejectedOn.isBefore(getProjectedCommencementDate())) { - - final String errorMessage = "The date on which a deposit is rejected cannot be before its submittal date: " - + getProjectedCommencementDate().toString(); - throw new InvalidDepositStateTransitionException("reject", "cannot.be.before.submittal.date", errorMessage, rejectedOn, - getProjectedCommencementDate()); - - } - if (rejectedOn.isAfter(new LocalDate())) { - - final String errorMessage = "The date on which a deposit is rejected cannot be in the future."; - throw new InvalidDepositStateTransitionException("reject", "cannot.be.a.future.date", errorMessage, rejectedOn); - - } - - } - - public void withdrawnByApplicant(final LocalDate withdrawnOn, final DepositLifecycleStateMachine depositLifecycleStateMachine) { - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_WITHDRAWN, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnum.getValue(); - - this.maturesOnDate = null; - this.withdrawnOnDate = withdrawnOn.toDateTimeAtCurrentTime().toDate(); - this.closedOnDate = withdrawnOn.toDateTimeAtCurrentTime().toDate(); - - if (withdrawnOn.isBefore(getProjectedCommencementDate())) { - - final String errorMessage = "The date on which a deposit is rejected cannot be before its submittal date: " - + getProjectedCommencementDate().toString(); - throw new InvalidDepositStateTransitionException("reject", "cannot.be.before.submittal.date", errorMessage, withdrawnOn, - getProjectedCommencementDate()); - - } - - if (withdrawnOn.isAfter(new LocalDate())) { - final String errorMessage = "The date on which a deposit is rejected cannot be in the future."; - throw new InvalidDepositStateTransitionException("reject", "cannot.be.a.future.date", errorMessage, withdrawnOn); - } - } - - public void undoDepositApproval(final DepositLifecycleStateMachine depositLifecycleStateMachine) { - - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_APPROVAL_UNDO, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnum.getValue(); - - this.actualCommencementDate = null; - this.projectedInterestAccruedOnMaturity = this.interestAccrued; - this.projectedTotalOnMaturity = this.depositAmount.add(this.projectedInterestAccruedOnMaturity); - this.maturesOnDate = getProjectedCommencementDate().plusMonths(this.tenureInMonths).minusDays(1).toDate(); - this.total = null; - this.interestAccrued = null; - this.depositaccountTransactions.clear(); - } - - public PeriodFrequencyType getInterestCompoundedFrequencyType() { - return PeriodFrequencyType.fromInt(this.interestCompoundedFrequencyType); - } - - public Money getDeposit() { - return Money.of(this.currency, this.depositAmount); - } - - public Money getAccuredInterest() { - return Money.of(this.currency, this.interestAccrued); - } - - public Client client() { - return this.client; - } - - public DepositProduct product() { - return this.product; - } - - public String getExternalId() { - return this.externalId; - } - - public boolean isRenewalAllowed() { - return this.renewalAllowed; - } - - public BigDecimal getInterstPaid() { - return this.interstPaid; - } - - public boolean isInterestWithdrawable() { - return isInterestWithdrawable; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public Integer getInterestCompoundedEvery() { - return this.interestCompoundedEvery; - } - - public BigDecimal getInterestRate() { - return interestRate; - } - - public Date getMaturesOnDate() { - return maturesOnDate; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public boolean isPreClosureAllowed() { - return preClosureAllowed; - } - - public Integer getDepositStatus() { - return depositStatus; - } - - public LocalDate maturesOnDate() { - LocalDate date = null; - if (this.maturesOnDate != null) { - date = new LocalDate(this.maturesOnDate); - } - return date; - } - - public void updateAccount(final DepositAccount account) { - - this.renewdAccount = account; - - } - - public void withdrawDepositAccountMoney(final DepositLifecycleStateMachine depositLifecycleStateMachine, - final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator, final LocalDate eventDate) { - - if (eventDate.isBefore(getLastInterestPostedDate())) { - final String errorMessage = "Deposit Account Preclosed date \"" + eventDate + "\"cannot before last interest posted date \"" - + getLastInterestPostedDate() + "\""; - throw new InvalidDepositStateTransitionException("withdraw", "event.date.cannot.before.last.interest.posted.date", - errorMessage, getLastInterestPostedDate(), eventDate); - } - if (eventDate.isAfter(maturesOnDate()) || eventDate.equals(maturesOnDate())) { - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CLOSED, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnum.getValue(); - } else if (eventDate.isBefore(maturesOnDate())) { - DepositAccountStatus statusEnum = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_PRECLOSED, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnum.getValue(); - } - - Integer days = Days.daysBetween(getLastInterestPostedDate(), eventDate).getDays(); - Money accuredInterestAfterMaturityToTillDate = fixedTermDepositInterestCalculator.calculateRemainInterest(getDeposit(), days, - preClosureInterestRate); - this.interestAccrued = this.interestAccrued.add(accuredInterestAfterMaturityToTillDate.getAmount()); - this.availableInterest = this.availableInterest.add(accuredInterestAfterMaturityToTillDate.getAmount()); - DepositAccountTransaction depositaccountTransaction = DepositAccountTransaction.withdraw(getDeposit(), eventDate, - Money.of(currency, this.availableInterest), getDeposit().getAmount().add(this.availableInterest)); - // DepositAccountTransaction depositaccountTransaction = - // DepositAccountTransaction.withdraw(getDeposit(), eventDate, - // getAccuredInterest()); - depositaccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositaccountTransaction); - - this.closedOnDate = eventDate.toDate(); - this.withdrawnOnDate = null; - this.rejectedOnDate = null; - - } - - /* - * public void adjustTotalAmountForPreclosureInterest(DepositAccount - * account, FixedTermDepositInterestCalculator - * fixedTermDepositInterestCalculator,LocalDate eventDate) { - * - * LocalDate commnencementDate = getActualCommencementDate(); LocalDate - * lastInterestPosedDate = getLastInterestPostedDate(); LocalDate - * preClosedDate = eventDate; - * - * if (preClosedDate.isBefore(lastInterestPosedDate)) { throw new - * DepositAccountTransactionsException - * ("deposit.account.preclosed.date.should.be.after.last.interest.posted.date" - * , null); } - * - * Integer tenure = Months.monthsBetween(lastInterestPosedDate, - * preClosedDate).getMonths(); LocalDate actualPrecloseCalculationDate = - * lastInterestPosedDate.plusMonths(tenure); Integer missedDays = - * Days.daysBetween(actualPrecloseCalculationDate, preClosedDate).getDays(); - * - * Money deposit = Money.of(account.getDeposit().getCurrency(), - * account.getDeposit().getAmount()); Money accuredtotalAmount = null; Money - * remainDaysAmount = - * fixedTermDepositInterestCalculator.calculateRemainInterest(deposit, - * missedDays, preClosureInterestRate); if - * (account.isInterestCompoundingAllowed()) { accuredtotalAmount = - * fixedTermDepositInterestCalculator - * .calculateInterestOnMaturityFor(deposit, tenure, preClosureInterestRate, - * interestCompoundedEvery, - * this.product.getInterestCompoundedEveryPeriodType()); accuredtotalAmount - * = accuredtotalAmount.plus(remainDaysAmount); } else { accuredtotalAmount - * = fixedTermDepositInterestCalculator - * .calculateInterestOnMaturityForSimpleInterest(deposit, tenure, - * preClosureInterestRate, interestCompoundedEvery, - * this.product.getInterestCompoundedEveryPeriodType()); accuredtotalAmount - * = accuredtotalAmount.plus(remainDaysAmount); } this.total = - * account.isInterestCompoundingAllowed - * ()?accuredtotalAmount.getAmount():BigDecimal - * .valueOf(accuredtotalAmount.getAmount - * ().doubleValue()-this.interstPaid.doubleValue()); this.interestAccrued = - * accuredtotalAmount.minus(deposit).getAmount(); - * - * } - */ - - public void withdrawInterest(final Money interest) { - @SuppressWarnings("unused") - boolean statustest = isActive(); - if (isActive()) { - // DepositAccountTransaction depositAccountTransaction = - // DepositAccountTransaction.withdraw(null, new LocalDate(), - // interest); - DepositAccountTransaction depositAccountTransaction = DepositAccountTransaction.withdraw(null, new LocalDate(), interest, - getDeposit().getAmount().add(this.availableInterest).subtract(interest.getAmount())); - depositAccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositAccountTransaction); - this.interstPaid = this.interstPaid.add(interest.getAmount()); - this.availableInterest = this.availableInterest.subtract(interest.getAmount()); - this.total = this.total.subtract(interest.getAmount()); - } - - } - - public void closeDepositAccount(final DepositLifecycleStateMachine depositLifecycleStateMachine) { - DepositAccountStatus statusEnumForClose = depositLifecycleStateMachine.transition(DepositAccountEvent.DEPOSIT_CLOSED, - DepositAccountStatus.fromInt(this.depositStatus)); - this.depositStatus = statusEnumForClose.getValue(); - - // DepositAccountTransaction depositaccountTransaction = - // DepositAccountTransaction.withdraw(getDeposit(), new - // LocalDate(),Money.of(getDeposit().getCurrency(), - // getTotal()).minus(getDeposit())); - DepositAccountTransaction depositaccountTransaction = DepositAccountTransaction.withdraw(getDeposit(), new LocalDate(), - Money.of(getDeposit().getCurrency(), getTotal()).minus(getDeposit()), - getDeposit().plus(Money.of(getDeposit().getCurrency(), getTotal()).minus(getDeposit())).getAmount()); - depositaccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositaccountTransaction); - - this.closedOnDate = new LocalDate().toDate(); - } - - public void update(final DepositProduct product, final String externalId, final LocalDate commencementDate, final Money deposit, - final Integer tenureInMonths, final BigDecimal maturityInterestRate, final BigDecimal preClosureInterestRate, - final Integer interestCompoundedEvery, final PeriodFrequencyType compoundingInterestFrequency, final boolean renewalAllowed, - final boolean preClosureAllowed, final boolean isInterestWithdrawable, final boolean isInterestCompoundingAllowed, - final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType) { - - Money futureValueOnMaturity = null; - - if (isInterestCompoundingAllowed) { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityFor(deposit, tenureInMonths, - maturityInterestRate, interestCompoundedEvery); - } else { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityForSimpleInterest(deposit, - tenureInMonths, maturityInterestRate, interestCompoundedEvery); - } - - setExternalId(externalId); - if (commencementDate != null) { - this.projectedCommencementDate = commencementDate.toDate(); - this.maturesOnDate = commencementDate.plusMonths(this.tenureInMonths).minusDays(1).toDate(); - } - this.product = product; - this.depositAmount = deposit.getAmount(); - this.tenureInMonths = tenureInMonths; - this.interestRate = maturityInterestRate; - this.product.validateInterestRateInRange(maturityInterestRate); - this.preClosureInterestRate = preClosureInterestRate; - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedFrequencyType = compoundingInterestFrequency.getValue(); - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - this.isInterestWithdrawable = isInterestWithdrawable; - this.interestCompoundingAllowed = isInterestCompoundingAllowed; - this.projectedInterestAccruedOnMaturity = futureValueOnMaturity.minus(deposit).getAmount(); - this.projectedTotalOnMaturity = futureValueOnMaturity.getAmount(); - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - this.interestAccrued = BigDecimal.ZERO; - - } - - public void update(final boolean renewalAllowed, final boolean isInterestWithdrawable) { - this.renewalAllowed = renewalAllowed; - this.isInterestWithdrawable = isInterestWithdrawable; - } - - public boolean isSubmittedAndPendingApproval() { - return DepositAccountStatus.fromInt(this.depositStatus).isSubmittedAndPendingApproval(); - } - - public boolean isActive() { - return DepositAccountStatus.fromInt(this.depositStatus).isActive(); - } - - public void postInterestForDepositAccount(final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator) { - - LocalDate lastInterestPostedDate = getLastInterestPostedDate(); - LocalDate nextInterestPostingDate = getNextInterestPostedDate(); - Integer monthsForInterestCalculation = Months.monthsBetween(lastInterestPostedDate, new LocalDate()).getMonths(); - Integer postInterestItereations = monthsForInterestCalculation / this.interestCompoundedEvery; - Money deposit = Money.of(this.currency, this.depositAmount); - - while (postInterestItereations > 0) { - - lastInterestPostedDate = getLastInterestPostedDate(); - nextInterestPostingDate = getNextInterestPostedDate(); - if (lastInterestPostedDate.isBefore(getMaturityDate())) { - if (nextInterestPostingDate.isAfter(getMaturityDate())) { - Integer noofRemainMonthsAfterMaturity = Months.monthsBetween(getMaturityDate(), nextInterestPostingDate).getMonths(); - Integer noOfMonthsBeforeMaturity = Months.monthsBetween(lastInterestPostedDate, getMaturityDate().plusDays(1)) - .getMonths(); - Money futureValueOnMaturity = Money.zero(this.currency); - if (noOfMonthsBeforeMaturity > 0) { - - if (this.interestCompoundingAllowed) { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityFor(deposit, - noOfMonthsBeforeMaturity, this.interestRate, this.interestCompoundedEvery); - } else { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityForSimpleInterest( - deposit, noOfMonthsBeforeMaturity, this.interestRate, this.interestCompoundedEvery); - } - this.interestPostedAmount = this.interestPostedAmount.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.availableInterest = this.availableInterest.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.lastInterestPostedDate = nextInterestPostingDate.toDate(); - this.nextInterestPostingDate = nextInterestPostingDate.plusMonths(this.interestCompoundedEvery).toDate(); - - } - if (noofRemainMonthsAfterMaturity > 0) { - - if (this.interestCompoundingAllowed) { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityFor(deposit, - noofRemainMonthsAfterMaturity, this.preClosureInterestRate, this.interestCompoundedEvery); - } else { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityForSimpleInterest( - deposit, noofRemainMonthsAfterMaturity, this.preClosureInterestRate, this.interestCompoundedEvery); - } - this.interestPostedAmount = this.interestPostedAmount.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.availableInterest = this.availableInterest.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.lastInterestPostedDate = nextInterestPostingDate.toDate(); - this.nextInterestPostingDate = nextInterestPostingDate.plusMonths(this.interestCompoundedEvery).toDate(); - } - - // add transaction entry for each interest posting - DepositAccountTransaction depositaccountTransaction = DepositAccountTransaction.postInterest(null, - nextInterestPostingDate, futureValueOnMaturity.minus(deposit), deposit.getAmount().add(this.availableInterest)); - - depositaccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositaccountTransaction); - } else { - Money futureValueOnMaturity = null; - if (this.interestCompoundingAllowed) { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityFor(deposit, - this.interestCompoundedEvery, this.interestRate, this.interestCompoundedEvery); - } else { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityForSimpleInterest(deposit, - this.interestCompoundedEvery, this.interestRate, this.interestCompoundedEvery); - } - this.interestPostedAmount = this.interestPostedAmount.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.availableInterest = this.availableInterest.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.lastInterestPostedDate = nextInterestPostingDate.toDate(); - this.nextInterestPostingDate = nextInterestPostingDate.plusMonths(this.interestCompoundedEvery).toDate(); - - // add transaction entry for each interest posting - DepositAccountTransaction depositaccountTransaction = DepositAccountTransaction.postInterest(null, - nextInterestPostingDate, futureValueOnMaturity.minus(deposit), deposit.getAmount().add(this.availableInterest)); - depositaccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositaccountTransaction); - } - } else { - Money futureValueOnMaturity = null; - if (this.interestCompoundingAllowed) { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityFor(deposit, - this.interestCompoundedEvery, this.preClosureInterestRate, this.interestCompoundedEvery); - } else { - futureValueOnMaturity = fixedTermDepositInterestCalculator.calculateInterestOnMaturityForSimpleInterest(deposit, - this.interestCompoundedEvery, this.preClosureInterestRate, this.interestCompoundedEvery); - } - this.interestPostedAmount = this.interestPostedAmount.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.availableInterest = this.availableInterest.add(futureValueOnMaturity.minus(deposit).getAmount()); - this.lastInterestPostedDate = nextInterestPostingDate.toDate(); - this.nextInterestPostingDate = nextInterestPostingDate.plusMonths(this.interestCompoundedEvery).toDate(); - - // add transaction entry for each interest posting - DepositAccountTransaction depositaccountTransaction = DepositAccountTransaction.postInterest(null, nextInterestPostingDate, - futureValueOnMaturity.minus(deposit), deposit.getAmount().add(this.availableInterest)); - depositaccountTransaction.updateAccount(this); - this.depositaccountTransactions.add(depositaccountTransaction); - } - postInterestItereations--; - } - - } - - private final LocalDate getLastInterestPostedDate() { - LocalDate lastInterestPostedDate; - if (this.lastInterestPostedDate == null) { - lastInterestPostedDate = new LocalDate(this.actualCommencementDate); - } else { - lastInterestPostedDate = new LocalDate(this.lastInterestPostedDate); - } - return lastInterestPostedDate; - } - - private final LocalDate getNextInterestPostedDate() { - LocalDate nextInterestPostingDate; - if (this.nextInterestPostingDate == null) { - nextInterestPostingDate = new LocalDate(this.nextInterestPostingDate).plusMonths(this.interestCompoundedEvery); - } else { - nextInterestPostingDate = new LocalDate(this.nextInterestPostingDate); - } - return nextInterestPostingDate; - } - - public BigDecimal getAvailableInterest() { - return availableInterest; - } - - public BigDecimal getInterestPostedAmount() { - return interestPostedAmount; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountEvent.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountEvent.java deleted file mode 100644 index 8a692743e..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountEvent.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -public enum DepositAccountEvent { - - DEPOSIT_CREATED, DEPOSIT_REJECTED, DEPOSIT_APPROVED, DEPOSIT_APPROVAL_UNDO, DEPOSIT_WITHDRAWN, DEPOSIT_MATURED, DEPOSIT_CLOSED, DEPOSIT_PRECLOSED; -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountStatus.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountStatus.java deleted file mode 100644 index cd738ab1b..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountStatus.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -public enum DepositAccountStatus { - - INVALID(0, "depositStatusType.invalid"), // - SUBMITED_AND_PENDING_APPROVAL(100, "depositStatusType.submitted.and.pending.approval"), // - // APPROVED(200, "depositStatusType.approved"), // - ACTIVE(300, "depositStatusType.active"), // - WITHDRAWN_BY_CLIENT(400, "depositStatusType.withdrawn.by.client"), // - REJECTED(500, "depositStatusType.rejected"), // - CLOSED(600, "depositStatusType.closed"), // - MATURED(700, "depositStatusType.matured"), PRECLOSED(800, "depositStatusType.preclosed"); - - private final Integer value; - private final String code; - - private DepositAccountStatus(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public boolean hasStateOf(final DepositAccountStatus state) { - return this.value.equals(state.getValue()); - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public boolean isSubmittedAndPendingApproval() { - return this.value.equals(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL.getValue()); - } - - /* - * public boolean isApproved() { return - * this.value.equals(DepositAccountStatus.APPROVED.getValue()); } - */ - - public boolean isActive() { - return this.value.equals(DepositAccountStatus.ACTIVE.getValue()); - } - - public boolean isClosed() { - return this.value.equals(DepositAccountStatus.CLOSED.getValue()); - } - - public boolean isWithdrawnByClient() { - return this.value.equals(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue()); - } - - public boolean isRejected() { - return this.value.equals(DepositAccountStatus.REJECTED.getValue()); - } - - public boolean isPreClosed() { - return this.value.equals(DepositAccountStatus.PRECLOSED.getValue()); - } - - public static DepositAccountStatus fromInt(final Integer statusValue) { - - DepositAccountStatus enumeration = DepositAccountStatus.INVALID; - switch (statusValue) { - case 100: - enumeration = DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL; - break; - /* - * case 200: enumeration = DepositAccountStatus.APPROVED; break; - */ - case 300: - enumeration = DepositAccountStatus.ACTIVE; - break; - case 400: - enumeration = DepositAccountStatus.WITHDRAWN_BY_CLIENT; - break; - case 500: - enumeration = DepositAccountStatus.REJECTED; - break; - case 600: - enumeration = DepositAccountStatus.CLOSED; - break; - case 700: - enumeration = DepositAccountStatus.MATURED; - break; - case 800: - enumeration = DepositAccountStatus.PRECLOSED; - break; - } - return enumeration; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransaction.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransaction.java deleted file mode 100644 index 4fa6a3c18..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransaction.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -import java.math.BigDecimal; -import java.util.Date; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.joda.time.LocalDate; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.springframework.data.jpa.domain.AbstractPersistable; - -@Entity -@Table(name = "m_deposit_account_transaction") -public class DepositAccountTransaction extends AbstractPersistable { - - @SuppressWarnings("unused") - @ManyToOne(optional = false) - @JoinColumn(name = "deposit_account_id", nullable = false) - private DepositAccount depositAccount; - - @Enumerated(EnumType.ORDINAL) - @Column(name = "transaction_type_enum", nullable = false) - private DepositAccountTransactionType typeOf; - - @SuppressWarnings("unused") - @OneToOne(optional = true, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "contra_id") - private DepositAccountTransaction contra; - - @Temporal(TemporalType.DATE) - @Column(name = "transaction_date", nullable = false) - private final Date dateOf; - - @Column(name = "amount", scale = 6, precision = 19, nullable = false) - private final BigDecimal amount; - - @SuppressWarnings("unused") - @Column(name = "interest", scale = 6, precision = 19, nullable = false) - private final BigDecimal interest; - - @SuppressWarnings("unused") - @Column(name = "total", scale = 6, precision = 19, nullable = false) - private final BigDecimal total; - - protected DepositAccountTransaction() { - this.depositAccount = null; - this.typeOf = null; - this.amount = null; - this.dateOf = null; - this.interest = null; - this.total = null; - } - - private DepositAccountTransaction(DepositAccountTransactionType type, final BigDecimal amount, final LocalDate date, - final BigDecimal interest) { - this.typeOf = type; - this.amount = amount; - this.dateOf = date.toDateMidnight().toDate(); - this.interest = interest; - this.total = amount.doubleValue() == 0 ? new BigDecimal(0) : amount.add(interest); - } - - private DepositAccountTransaction(DepositAccountTransactionType type, final BigDecimal amount, final LocalDate date, final BigDecimal interest, final BigDecimal total) { - this.typeOf = type; - this.amount = amount; - this.dateOf = date.toDateMidnight().toDate(); - this.interest = interest; - this.total = total; - } - - public Date getDateOf() { - return dateOf; - } - - public BigDecimal getAmount() { - return amount; - } - - public DepositAccountTransactionType getTypeOf() { - return typeOf; - } - - public Money getAmount(MonetaryCurrency currency) { - return Money.of(currency, this.amount); - } - - public LocalDate getTransactionDate() { - return new LocalDate(this.dateOf); - } - - public boolean isDeposit() { - return DepositAccountTransactionType.DEPOSIT.equals(typeOf); - } - - 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()); - } - - /* public static DepositAccountTransaction withdraw(Money amount, LocalDate paymentDate, Money interest) { - return new DepositAccountTransaction(DepositAccountTransactionType.WITHDRAW, amount == null ? new BigDecimal(0) - : amount.getAmount(), paymentDate, interest == null ? new BigDecimal(0) : interest.getAmount()); - } - - public static DepositAccountTransaction 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()); - }*/ - - public static DepositAccountTransaction withdraw(Money amount, LocalDate paymentDate, Money interest, BigDecimal total) { - return new DepositAccountTransaction(DepositAccountTransactionType.WITHDRAW, amount == null ? new BigDecimal(0) : amount.getAmount(), paymentDate, interest==null ? new BigDecimal(0) : interest.getAmount(),total); - - } - - public static DepositAccountTransaction postInterest(Money depositAmount, LocalDate paymentDate, Money interest, BigDecimal total) { - return new DepositAccountTransaction(DepositAccountTransactionType.INTEREST_POSTING, depositAmount == null ? new BigDecimal(0) : depositAmount.getAmount(), paymentDate, interest==null ? new BigDecimal(0) : interest.getAmount(),total); - - } - - public void updateAccount(DepositAccount depositAccount) { - this.depositAccount = depositAccount; - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransactionType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransactionType.java deleted file mode 100644 index ec8583a0d..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositAccountTransactionType.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -public enum DepositAccountTransactionType { - - INVALID(0, "depositTransactionType.invalid"), // - DEPOSIT(1, "depositTransactionType.deposit"), // - WITHDRAW(2, "depositTransactionType.withdraw"), // - REVERSAL(3, "depositTransactionType.reversal"), INTEREST_POSTING(4, "depositTransactionType.interestPosting"); - - - private final Integer value; - private final String code; - - private DepositAccountTransactionType(final Integer value, final String code) { - - this.value=value; - this.code=code; - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public static DepositAccountTransactionType fromInt(final Integer transactionType){ - - if (transactionType == null) { - return DepositAccountTransactionType.INVALID; - } - - DepositAccountTransactionType depositTransactionType=null; - switch (transactionType) { - case 1: - depositTransactionType=DepositAccountTransactionType.DEPOSIT; - break; - - case 2: - depositTransactionType=DepositAccountTransactionType.WITHDRAW; - break; - - case 3: - depositTransactionType=DepositAccountTransactionType.REVERSAL; - break; - - case 4: - depositTransactionType=DepositAccountTransactionType.INTEREST_POSTING; - break; - - default : - depositTransactionType=DepositAccountTransactionType.INVALID; - break; - - } - - return depositTransactionType; - } - - public boolean isDeposit() { - return this.value.equals(DepositAccountTransactionType.DEPOSIT.value); - } - - public boolean isWithdraw() { - return this.value.equals(DepositAccountTransactionType.WITHDRAW.value); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachine.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachine.java deleted file mode 100644 index 0004b2ffc..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachine.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -public interface DepositLifecycleStateMachine { - - DepositAccountStatus transition(DepositAccountEvent loanEvent, DepositAccountStatus from); -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachineImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachineImpl.java deleted file mode 100644 index 1d1ab15fa..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/DepositLifecycleStateMachineImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -import java.util.List; - -import org.mifosplatform.portfolio.savingsdepositaccount.exception.InvalidDepositStateTransitionException; - -public class DepositLifecycleStateMachineImpl implements DepositLifecycleStateMachine { - - private final List allowedDepositStatuses; - - public DepositLifecycleStateMachineImpl(List allowedDepositStatuses) { - this.allowedDepositStatuses = allowedDepositStatuses; - } - - @Override - public DepositAccountStatus transition(DepositAccountEvent depositEvent, DepositAccountStatus from) { - - DepositAccountStatus newState = null; - - switch (depositEvent) { - case DEPOSIT_CREATED: - if (from == null) { - newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses); - } - break; - case DEPOSIT_REJECTED: - if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) { - newState = stateOf(DepositAccountStatus.REJECTED, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be rejected from " + from.getCode(); - throw new InvalidDepositStateTransitionException("rejection", "failed", errorMessage, from); - } - break; - case DEPOSIT_APPROVED: - if (from.hasStateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL)) { - newState = stateOf(DepositAccountStatus.ACTIVE, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be approved from " + from.getCode(); - throw new InvalidDepositStateTransitionException("approve", "failed", errorMessage, from); - } - break; - case DEPOSIT_WITHDRAWN: - if (this.anyOfAllowedWhenComingFrom(from, DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, DepositAccountStatus.ACTIVE)) { - newState = stateOf(DepositAccountStatus.WITHDRAWN_BY_CLIENT, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be withdrawn from " + from.getCode(); - throw new InvalidDepositStateTransitionException("withdrawbyclient", "failed", errorMessage, from); - } - break; - case DEPOSIT_APPROVAL_UNDO: - if (from.hasStateOf(DepositAccountStatus.ACTIVE)) { - newState = stateOf(DepositAccountStatus.SUBMITED_AND_PENDING_APPROVAL, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be unapproved from " + from.getCode(); - throw new InvalidDepositStateTransitionException("unapprove", "failed", errorMessage, from); - } - break; - case DEPOSIT_MATURED: - if (from.hasStateOf(DepositAccountStatus.ACTIVE)) { - newState = stateOf(DepositAccountStatus.MATURED, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be matured from " + from.getCode(); - throw new InvalidDepositStateTransitionException("mature", "failed", errorMessage, from); - } - break; - case DEPOSIT_CLOSED: - if (from.hasStateOf(DepositAccountStatus.ACTIVE)) { - newState = stateOf(DepositAccountStatus.CLOSED, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be closed from " + from.getCode(); - throw new InvalidDepositStateTransitionException("closed", "failed", errorMessage, from); - } - break; - case DEPOSIT_PRECLOSED: - if (from.hasStateOf(DepositAccountStatus.ACTIVE)) { - newState = stateOf(DepositAccountStatus.PRECLOSED, allowedDepositStatuses); - } else { - final String errorMessage = "The DepositApplication can not be matured from " + from.getCode(); - throw new InvalidDepositStateTransitionException("preclosure", "failed", errorMessage, from); - } - break; - default: - break; - - } - - return newState; - } - - private DepositAccountStatus stateOf(DepositAccountStatus state, List allowedLoanStatuses) { - DepositAccountStatus match = null; - for (DepositAccountStatus depositStatus : allowedLoanStatuses) { - if (depositStatus.hasStateOf(state)) { - match = depositStatus; - break; - } - } - return match; - } - - private boolean anyOfAllowedWhenComingFrom(final DepositAccountStatus state, final DepositAccountStatus... allowedStates) { - boolean allowed = false; - - for (DepositAccountStatus allowedState : allowedStates) { - if (state.hasStateOf(allowedState)) { - allowed = true; - break; - } - } - - return allowed; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/FixedTermDepositInterestCalculator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/FixedTermDepositInterestCalculator.java deleted file mode 100644 index 48114a839..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/domain/FixedTermDepositInterestCalculator.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.domain; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -import org.mifosplatform.organisation.monetary.domain.Money; -import org.springframework.stereotype.Service; - -@Service -public class FixedTermDepositInterestCalculator { - - public Money calculateInterestOnMaturityFor(final Money deposit, final Integer tenureInMonths, final BigDecimal maturityInterestRate, - final Integer interestCompoundedEvery) { - - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - Integer monthsInYear = 12; - - BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc); - BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc); - - BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()), - mc); - - Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery; - - return fv(ratePerCompoundingPeriod, numberOfPeriods, deposit); - } - - private static Money fv(final BigDecimal ratePerCompoundingPeriod, final Integer numberOfPeriods, final Money presentValue) { - - double pmtPerPeriod = Double.valueOf("0.0"); - double pv = presentValue.negated().getAmount().doubleValue(); - - double futureValue = fv(ratePerCompoundingPeriod.doubleValue(), numberOfPeriods.doubleValue(), pmtPerPeriod, pv, false); - - return Money.of(presentValue.getCurrency(), BigDecimal.valueOf(futureValue)); - } - - /** - * Future value of an amount given the number of payments, rate, amount of - * individual payment, present value and boolean value indicating whether - * payments are due at the beginning of period (false => payments are due at - * end of period) - */ - private static double fv(final double ratePeriodCompoundingPeriod, final double numberOfCompoundingPeriods, final double pmtPerPeriod, - final double presentValue, final boolean type) { - double retval = 0; - if (ratePeriodCompoundingPeriod == 0) { - retval = -1 * (presentValue + (numberOfCompoundingPeriods * pmtPerPeriod)); - } else { - double r1 = ratePeriodCompoundingPeriod + 1; - retval = ((1 - Math.pow(r1, numberOfCompoundingPeriods)) * (type ? r1 : 1) * pmtPerPeriod) / ratePeriodCompoundingPeriod - - presentValue * Math.pow(r1, numberOfCompoundingPeriods); - } - return retval; - } - - public Money calculateInterestOnMaturityForSimpleInterest(final Money deposit, final Integer tenureInMonths, - final BigDecimal maturityInterestRate, final Integer interestCompoundedEvery) { - - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - Integer monthsInYear = 12; - - BigDecimal interestRateAsFraction = maturityInterestRate.divide(BigDecimal.valueOf(100), mc); - BigDecimal interestRateForOneMonth = interestRateAsFraction.divide(BigDecimal.valueOf(monthsInYear.doubleValue()), mc); - BigDecimal ratePerCompoundingPeriod = interestRateForOneMonth.multiply(BigDecimal.valueOf(interestCompoundedEvery.doubleValue()), - mc); - Integer numberOfPeriods = tenureInMonths / interestCompoundedEvery; - - BigDecimal interest = ratePerCompoundingPeriod.multiply(deposit.getAmount()).multiply( - BigDecimal.valueOf(new Double(numberOfPeriods))); - BigDecimal totalAmount = deposit.getAmount().add(interest); - - return Money.of(deposit.getCurrency(), totalAmount); - } - - public Money calculateRemainInterest(final Money deposit, final Integer days, final BigDecimal interestRate) { - - MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - Integer daysInYear = 365; - - BigDecimal interestRateAsFraction = interestRate.divide(BigDecimal.valueOf(100), mc); - BigDecimal interestRateForOneDay = interestRateAsFraction.divide(BigDecimal.valueOf(daysInYear.doubleValue()), mc); - BigDecimal interest = BigDecimal.valueOf(deposit.getAmount().doubleValue() * days.doubleValue() - * interestRateForOneDay.doubleValue()); - - return Money.of(deposit.getCurrency(), interest); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccounDataValidationtException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccounDataValidationtException.java deleted file mode 100644 index d5b3e640e..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccounDataValidationtException.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.exception; - -import java.math.BigDecimal; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - -public class DepositAccounDataValidationtException extends 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); - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountReopenException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountReopenException.java deleted file mode 100644 index 1e8de99df..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountReopenException.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.exception; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.exception.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); - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountTransactionsException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountTransactionsException.java deleted file mode 100644 index 7c544942f..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/DepositAccountTransactionsException.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.exception; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - -public class DepositAccountTransactionsException extends AbstractPlatformDomainRuleException { - - public DepositAccountTransactionsException(String errorcode, String remainInterestForWithdrawal) { - super(errorcode, "You can Withdraw " + remainInterestForWithdrawal + " only", remainInterestForWithdrawal); - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidDepositStateTransitionException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidDepositStateTransitionException.java deleted file mode 100644 index 638855cff..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidDepositStateTransitionException.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.exception; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - -public class InvalidDepositStateTransitionException extends AbstractPlatformDomainRuleException { - - public InvalidDepositStateTransitionException(final String action, String postFix, String defaultUserMessage, - Object... defaultUserMessageArgs) { - super("error.msg.deposit." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidSavingStateTransitionException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidSavingStateTransitionException.java deleted file mode 100644 index 786d43055..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/exception/InvalidSavingStateTransitionException.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.exception; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - -public class InvalidSavingStateTransitionException extends AbstractPlatformDomainRuleException { - - public InvalidSavingStateTransitionException(final String action, String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg.saving." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/ApproveDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/ApproveDepositAccountCommandHandler.java deleted file mode 100644 index 3a69f04da..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/ApproveDepositAccountCommandHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ApproveDepositAccountCommandHandler implements NewCommandSourceHandler { - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public ApproveDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.approveDepositApplication(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/CreateDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/CreateDepositAccountCommandHandler.java deleted file mode 100644 index 1d6401e6d..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/CreateDepositAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class CreateDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public CreateDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.createDepositAccount(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/DeleteDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/DeleteDepositAccountCommandHandler.java deleted file mode 100644 index 2205e9ebb..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/DeleteDepositAccountCommandHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class DeleteDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public DeleteDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.deleteDepositAccount(command.entityId()); - } - - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RejectDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RejectDepositAccountCommandHandler.java deleted file mode 100644 index bebe4e1a9..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RejectDepositAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class RejectDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public RejectDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.rejectDepositApplication(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RenewDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RenewDepositAccountCommandHandler.java deleted file mode 100644 index 766385118..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/RenewDepositAccountCommandHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class RenewDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public RenewDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.renewDepositAccount(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UndoApprovalDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UndoApprovalDepositAccountCommandHandler.java deleted file mode 100644 index 8eb0cc2be..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UndoApprovalDepositAccountCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UndoApprovalDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public UndoApprovalDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.undoDepositApproval(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UpdateDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UpdateDepositAccountCommandHandler.java deleted file mode 100644 index 83f026786..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/UpdateDepositAccountCommandHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UpdateDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public UpdateDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.updateDepositAccount(command.entityId(), command); - } - - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithDrawByApplicantDepositAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithDrawByApplicantDepositAccountCommandHandler.java deleted file mode 100644 index 94f0e8a00..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithDrawByApplicantDepositAccountCommandHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class WithDrawByApplicantDepositAccountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public WithDrawByApplicantDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.withdrawDepositApplication(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawDepositAccountAmountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawDepositAccountAmountCommandHandler.java deleted file mode 100644 index 3fb272d96..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawDepositAccountAmountCommandHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class WithdrawDepositAccountAmountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public WithdrawDepositAccountAmountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.withdrawDepositAccountMoney(command); - } - - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawInterestDepositAccountAmountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawInterestDepositAccountAmountCommandHandler.java deleted file mode 100644 index bd84c0cb7..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/handler/WithdrawInterestDepositAccountAmountCommandHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.service.DepositAccountWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class WithdrawInterestDepositAccountAmountCommandHandler implements NewCommandSourceHandler { - - private final DepositAccountWritePlatformService depositAccountWritePlatformService; - - @Autowired - public WithdrawInterestDepositAccountAmountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { - this.depositAccountWritePlatformService = depositAccountWritePlatformService; - } - - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositAccountWritePlatformService.withdrawDepositAccountInterestMoney(command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountCommandFromApiJsonDeserializer.java deleted file mode 100644 index 97464643a..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountCommandFromApiJsonDeserializer.java +++ /dev/null @@ -1,247 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public class DepositAccountCommandFromApiJsonDeserializer { - - /** - * The parameters supported for this command. - */ - - private final Set supportedParams = new HashSet(Arrays.asList("clientId", "productId", "externalId", "deposit", - "maturityInterestRate", "preClosureInterestRate", "tenureInMonths", "interestCompoundedEvery", - "interestCompoundedEveryPeriodType", "commencementDate", "renewalAllowed", "preClosureAllowed", - "interestCompoundingAllowed", "locale", "dateFormat", "isInterestWithdrawable", "isLockinPeriodAllowed", "lockinPeriod", - "lockinPeriodType","note")); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public DepositAccountCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForCreate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - baseDataValidator.reset().parameter("clientId").value(clientId).notNull(); - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).notNull(); - - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).ignoreIfNull().notExceedingLengthOf(100); - - final BigDecimal deposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deposit", element); - baseDataValidator.reset().parameter("deposit").value(deposit).notNull().zeroOrPositiveAmount(); - - final Integer tenureInMonths = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureInMonths").value(tenureInMonths).notNull().zeroOrPositiveAmount(); - - final BigDecimal maturityInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maturityInterestRate", element); - baseDataValidator.reset().parameter("maturityInterestRate").value(maturityInterestRate).notNull().zeroOrPositiveAmount(); - - final Integer interestCompoundedEvery = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEvery").value(interestCompoundedEvery).notNull().zeroOrPositiveAmount(); - - final Integer interestCompoundedEveryPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEveryPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(interestCompoundedEveryPeriodType).notNull().inMinMaxRange(1, 3); - - final BigDecimal preClosureInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("preClosureInterestRate", element); - baseDataValidator.reset().parameter("preClosureInterestRate").value(preClosureInterestRate).notNull().zeroOrPositiveAmount(); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).notNull(); - - final Boolean isInterestWithdrawable = fromApiJsonHelper.extractBooleanNamed("isInterestWithdrawable", element); - final Boolean isInterestWithdrawableChanged = isBooleanValueUpdated(isInterestWithdrawable); - baseDataValidator.reset().parameter("isInterestWithdrawable").trueOrFalseRequired(isInterestWithdrawableChanged); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - - private Boolean isBooleanValueUpdated(Boolean actualValue) { - Boolean isUpdated = false; - if(actualValue != null){ - isUpdated = true; - } - return isUpdated; - } - - public void validateForApprove(String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).notNull(); - - final BigDecimal deposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deposit", element); - baseDataValidator.reset().parameter("deposit").value(deposit).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal maturityInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maturityInterestRate", element); - baseDataValidator.reset().parameter("maturityInterestRate").value(maturityInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer tenureInMonths = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureInMonths").value(tenureInMonths).ignoreIfNull().integerGreaterThanZero(); - - final Integer interestCompoundedEveryPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEveryPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(interestCompoundedEveryPeriodType).ignoreIfNull().inMinMaxRange(2, 2); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForRenew(String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - baseDataValidator.reset().parameter("clientId").value(clientId).ignoreIfNull(); - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).ignoreIfNull(); - - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).ignoreIfNull().notExceedingLengthOf(100); - - final BigDecimal deposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deposit", element); - baseDataValidator.reset().parameter("deposit").value(deposit).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal maturityInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maturityInterestRate", element); - baseDataValidator.reset().parameter("maturityInterestRate").value(maturityInterestRate).ignoreIfNull() - .zeroOrPositiveAmount(); - - final BigDecimal preClosureInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("preClosureInterestRate", element); - baseDataValidator.reset().parameter("preClosureInterestRate").value(preClosureInterestRate).ignoreIfNull() - .zeroOrPositiveAmount(); - - final Integer tenureInMonths = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureInMonths").value(tenureInMonths).ignoreIfNull().integerGreaterThanZero(); - - final Integer interestCompoundedEvery = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEvery").value(interestCompoundedEvery).ignoreIfNull() - .integerGreaterThanZero(); - - final Integer interestCompoundedEveryPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEveryPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(interestCompoundedEveryPeriodType) - .ignoreIfNull().inMinMaxRange(2, 2); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).ignoreIfNull(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - - public void validateForUpdate(String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - baseDataValidator.reset().parameter("clientId").value(clientId).ignoreIfNull(); - - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).ignoreIfNull(); - - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).ignoreIfNull().notExceedingLengthOf(100); - - final BigDecimal deposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deposit", element); - baseDataValidator.reset().parameter("deposit").value(deposit).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer tenureInMonths = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureInMonths").value(tenureInMonths).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal maturityInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maturityInterestRate", element); - baseDataValidator.reset().parameter("maturityInterestRate").value(maturityInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer interestCompoundedEvery = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEvery", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEvery").value(interestCompoundedEvery).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer interestCompoundedEveryPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEveryPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(interestCompoundedEveryPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - final BigDecimal preClosureInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("preClosureInterestRate", element); - baseDataValidator.reset().parameter("preClosureInterestRate").value(preClosureInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - baseDataValidator.reset().parameter("commencementDate").value(commencementDate).ignoreIfNull(); - - final Boolean isInterestWithdrawable = fromApiJsonHelper.extractBooleanNamed("isInterestWithdrawable", element); - final Boolean isInterestWithdrawableChanged = isBooleanValueUpdated(isInterestWithdrawable); - baseDataValidator.reset().parameter("isInterestWithdrawable").trueOrFalseRequired(isInterestWithdrawableChanged); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountStateTransitionCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountStateTransitionCommandFromApiJsonDeserializer.java deleted file mode 100644 index 74b130044..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/serialization/DepositAccountStateTransitionCommandFromApiJsonDeserializer.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositaccount.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public class DepositAccountStateTransitionCommandFromApiJsonDeserializer { - - /** - * The parameters supported for this command. - */ - - private final Set supportedParams = new HashSet(Arrays.asList("eventDate", "locale", "dateFormat", "note", "maturesOnDate", "amount" )); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public DepositAccountStateTransitionCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForReject(String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate eventDate = fromApiJsonHelper.extractLocalDateNamed("eventDate", element); - baseDataValidator.reset().parameter("eventDate").value(eventDate).notNull(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - - public void validateForWithdrawDepositApplication(String json) { - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate eventDate = fromApiJsonHelper.extractLocalDateNamed("eventDate", element); - baseDataValidator.reset().parameter("eventDate").value(eventDate).notNull(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForWithdrawDepositAmount(String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final LocalDate maturesOnDate = fromApiJsonHelper.extractLocalDateNamed("maturesOnDate", element); - baseDataValidator.reset().parameter("maturesOnDate").value(maturesOnDate).notNull(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForWithdrawInterestAmount(String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element); - baseDataValidator.reset().parameter("deposit").value(amount).notNull().zeroOrPositiveAmount(); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountAssembler.java deleted file mode 100644 index e274aa4e3..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountAssembler.java +++ /dev/null @@ -1,521 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.client.domain.Client; -import org.mifosplatform.portfolio.client.domain.ClientRepository; -import org.mifosplatform.portfolio.client.exception.ClientNotFoundException; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositAccountCommand; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccount; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountStatus; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachine; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachineImpl; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.FixedTermDepositInterestCalculator; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccounDataValidationtException; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.DepositProduct; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.DepositProductRepository; -import org.mifosplatform.portfolio.savingsdepositproduct.exception.DepositProductNotFoundException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.google.gson.JsonElement; - -/** - * An assembler for turning {@link DepositAccountCommand} into - * {@link DepositAccount}'s. - */ -@Service -public class DepositAccountAssembler { - - private final ClientRepository clientRepository; - private final DepositProductRepository depositProductRepository; - private final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator; - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public DepositAccountAssembler(final ClientRepository clientRepository, final DepositProductRepository depositProductRepository, - final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator, final FromJsonHelper fromApiJsonHelper) { - this.clientRepository = clientRepository; - this.depositProductRepository = depositProductRepository; - this.fixedTermDepositInterestCalculator = fixedTermDepositInterestCalculator; - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public DepositAccount assembleFrom(final JsonCommand command) { - final JsonElement element = command.parsedJson(); - - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - final Boolean isInterestWithdrawable = fromApiJsonHelper.extractBooleanNamed("isInterestWithdrawable", element); - final BigDecimal depositValue = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deposit", element); - final Integer tenureInMonthsCommandValue = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - final BigDecimal maturityInterestRateCommandValue = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maturityInterestRate", - element); - final BigDecimal preClosureInterestRateCommandValue = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("preClosureInterestRate", - element); - final Integer interestCompoundedEveryCommandValue = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEvery", element, - Locale.getDefault()); - final Integer interestCompoundedEveryPeriodTypeCommandValue = fromApiJsonHelper.extractIntegerNamed( - "interestCompoundedEveryPeriodType", element, Locale.getDefault()); - final Boolean renewalAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("renewalAllowed", element); - final Boolean preClosureAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("preClosureAllowed", element); - final Boolean interestCompoundingAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("interestCompoundingAllowed", element); - final Boolean isLockinPeriodAllowedCommandValue = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - final Integer lockinPeriodCommandValue = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - final Integer lockinPeriodTypeCommandValue = fromApiJsonHelper - .extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - final LocalDate commencementDate = fromApiJsonHelper.extractLocalDateNamed("commencementDate", element); - - Client client = this.clientRepository.findOne(clientId); - if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } - - DepositProduct product = this.depositProductRepository.findOne(productId); - if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(productId); } - - // details inherited from product setting (unless allowed to be - // overridden through account creation api - Money deposit = Money.of(product.getCurrency(), depositValue); - - Integer tenureInMonths = product.getTenureInMonths(); - if (tenureInMonthsCommandValue != null) { - tenureInMonths = tenureInMonthsCommandValue; - } - - BigDecimal maturityInterestRate = product.getDefaultInterestRate(); - if (maturityInterestRateCommandValue != null) { - maturityInterestRate = maturityInterestRateCommandValue; - } - - BigDecimal preClosureInterestRate = product.getPreClosureInterestRate(); - if (preClosureInterestRateCommandValue != null) { - preClosureInterestRate = preClosureInterestRateCommandValue; - } - - if (product.getMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException( - preClosureInterestRate, product.getMinInterestRate()); } - - Integer compoundingInterestEvery = product.getInterestCompoundedEvery(); - if (interestCompoundedEveryCommandValue != null) { - compoundingInterestEvery = interestCompoundedEveryCommandValue; - } - - PeriodFrequencyType compoundingInterestFrequency = product.getInterestCompoundedEveryPeriodType(); - if (interestCompoundedEveryPeriodTypeCommandValue != null) { - compoundingInterestFrequency = PeriodFrequencyType.fromInt(interestCompoundedEveryPeriodTypeCommandValue); - } - - boolean renewalAllowed = product.isRenewalAllowed(); - if (isBooleanValueUpdated(renewalAllowedCommandValue)) { - renewalAllowed = renewalAllowedCommandValue; - } - - boolean preClosureAllowed = product.isPreClosureAllowed(); - if (isBooleanValueUpdated(preClosureAllowedCommandValue)) { - preClosureAllowed = preClosureAllowedCommandValue; - } - - boolean interestCompoundingAllowed = product.isInterestCompoundingAllowed(); - if (isBooleanValueUpdated(interestCompoundingAllowedCommandValue)) { - interestCompoundingAllowed = interestCompoundingAllowedCommandValue; - } - - boolean isLockinPeriodAllowed = product.isLockinPeriodAllowed(); - if (isBooleanValueUpdated(isLockinPeriodAllowedCommandValue)) { - isLockinPeriodAllowed = isLockinPeriodAllowedCommandValue; - } - - Integer lockinPeriod = product.getLockinPeriod(); - if (lockinPeriodCommandValue != null) { - lockinPeriod = lockinPeriodCommandValue; - } - - PeriodFrequencyType lockinPeriodType = product.getLockinPeriodType(); - if (lockinPeriodTypeCommandValue != null) { - lockinPeriodType = PeriodFrequencyType.fromInt(lockinPeriodTypeCommandValue); - } - // end of details allowed to be overriden from product - - DepositAccount account = new DepositAccount().openNew(client, product, externalId, deposit, maturityInterestRate, - preClosureInterestRate, tenureInMonths, compoundingInterestEvery, compoundingInterestFrequency, commencementDate, - renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator, defaultDepositLifecycleStateMachine(), - isInterestWithdrawable, interestCompoundingAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType); - - return account; - } - - private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() { - List allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values()); - return new DepositLifecycleStateMachineImpl(allowedDepositStatuses); - } - - - public DepositAccount assembleFrom(DepositAccount account, JsonCommand command, Map actualChanges) { - - final String localeAsInput = command.locale(); - - Client client = account.client(); - - DepositProduct product = account.product(); - final String productIdParamName = "productId"; - if (command.isChangeInLongParameterNamed(productIdParamName, account.product().getId())) { - final Long newValue = command.longValueOfParameterNamed(productIdParamName); - if (newValue != null) { - product = this.depositProductRepository.findOne(newValue); - if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(newValue); } - } - actualChanges.put(productIdParamName, newValue); - actualChanges.put("locale", localeAsInput); - } - - Money deposit = account.getDeposit(); - final String depositParamName = "deposit"; - if (command.isChangeInBigDecimalParameterNamed(depositParamName, deposit.getAmount())) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(depositParamName); - actualChanges.put(depositParamName, newValue); - actualChanges.put("locale", localeAsInput); - deposit = Money.of(deposit.getCurrency(), newValue); - } - - Integer tenureInMonths = account.getTenureInMonths(); - final String tenureInMonthsParamName = "tenureInMonths"; - if (command.isChangeInIntegerParameterNamed(tenureInMonthsParamName, tenureInMonths)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureInMonthsParamName); - actualChanges.put(tenureInMonthsParamName, newValue); - actualChanges.put("locale", localeAsInput); - tenureInMonths = newValue; - } - - BigDecimal maturityInterestRate = account.getInterestRate(); - final String maturityInterestRateParamName = "maturityInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(maturityInterestRateParamName, maturityInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(maturityInterestRateParamName); - actualChanges.put(maturityInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - maturityInterestRate = newValue; - } - - BigDecimal preClosureInterestRate = account.getPreClosureInterestRate(); - final String preClosureInterestRateParamName = "preClosureInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(preClosureInterestRateParamName, preClosureInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(preClosureInterestRateParamName); - actualChanges.put(preClosureInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - preClosureInterestRate = newValue; - } - - if (product.getMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException( - preClosureInterestRate, product.getMinInterestRate()); } - - Integer interestCompoundedEvery = account.getInterestCompoundedEvery(); - final String interestCompoundedEveryParamName = "interestCompoundedEvery"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryParamName, interestCompoundedEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryParamName); - actualChanges.put(interestCompoundedEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestCompoundedEvery = newValue; - } - - PeriodFrequencyType interestCompoundedEveryPeriodType = account.getInterestCompoundedFrequencyType(); - final String interestCompoundedEveryPeriodTypeParamName = "interestCompoundedEveryPeriodType"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryPeriodTypeParamName, - interestCompoundedEveryPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryPeriodTypeParamName); - actualChanges.put(interestCompoundedEveryPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestCompoundedEveryPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - Boolean renewalAllowed = account.isRenewalAllowed(); - final String renewalAllowedParamName = "renewalAllowed"; - if (command.isChangeInBooleanParameterNamed(renewalAllowedParamName, renewalAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(renewalAllowedParamName); - actualChanges.put(renewalAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - renewalAllowed = newValue; - } - - Boolean preClosureAllowed = account.isPreClosureAllowed(); - final String preClosureAllowedParamName = "preClosureAllowed"; - if (command.isChangeInBooleanParameterNamed(preClosureAllowedParamName, preClosureAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(preClosureAllowedParamName); - actualChanges.put(preClosureAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - preClosureAllowed = newValue; - } - - Boolean isInterestWithdrawable = account.isInterestWithdrawable(); - final String isInterestWithdrawableParamName = "isInterestWithdrawable"; - if (command.isChangeInBooleanParameterNamed(isInterestWithdrawableParamName, isInterestWithdrawable)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isInterestWithdrawableParamName); - actualChanges.put(isInterestWithdrawableParamName, newValue); - actualChanges.put("locale", localeAsInput); - isInterestWithdrawable = newValue; - } - - Boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed(); - final String isInterestCompoundingAllowedParamName = "interestCompoundingAllowed"; - if (command.isChangeInBooleanParameterNamed(isInterestCompoundingAllowedParamName, isInterestCompoundingAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isInterestCompoundingAllowedParamName); - actualChanges.put(isInterestCompoundingAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - isInterestCompoundingAllowed = newValue; - } - - Boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); - final String isLockinPeriodAllowedParamName = "isLockinPeriodAllowed"; - if (command.isChangeInBooleanParameterNamed(isLockinPeriodAllowedParamName, isLockinPeriodAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isLockinPeriodAllowedParamName); - actualChanges.put(isLockinPeriodAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - isLockinPeriodAllowed = newValue; - } - - Integer lockinPeriod = account.getLockinPeriod(); - final String lockinPeriodParamName = "lockinPeriod"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodParamName, lockinPeriod)) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodParamName); - actualChanges.put(lockinPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - lockinPeriod = newValue; - } - - PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType(); - final String lockinPeriodTypeParamName = "lockinPeriodType"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodTypeParamName, lockinPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodTypeParamName); - actualChanges.put(lockinPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - lockinPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - DepositAccount newAccount = new DepositAccount().openNew(client, product, null, deposit, maturityInterestRate, - preClosureInterestRate, tenureInMonths, interestCompoundedEvery, interestCompoundedEveryPeriodType, account.maturesOnDate() - .plusDays(1), renewalAllowed, preClosureAllowed, this.fixedTermDepositInterestCalculator, - defaultDepositLifecycleStateMachine(), isInterestWithdrawable, isInterestCompoundingAllowed, isLockinPeriodAllowed, - lockinPeriod, lockinPeriodType); - - newAccount.updateAccount(account); - - return newAccount; - } - - public Map assembleUpdatedDepositAccount(final DepositAccount account, final JsonCommand command) { - - final Map actualChanges = new LinkedHashMap(20); - final String localeAsInput = command.locale(); - - DepositProduct product = account.product(); - final String productIdParamName = "productId"; - if (command.isChangeInLongParameterNamed(productIdParamName, account.product().getId())) { - final Long newValue = command.longValueOfParameterNamed(productIdParamName); - if (newValue != null) { - product = this.depositProductRepository.findOne(newValue); - if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(newValue); } - } - actualChanges.put(productIdParamName, newValue); - actualChanges.put("locale", localeAsInput); - } - - String externalId = account.getExternalId(); - final String externalIdParamName = "externalId"; - if (command.isChangeInStringParameterNamed(externalIdParamName, externalId)) { - final String newValue = command.stringValueOfParameterNamed(externalIdParamName); - actualChanges.put(externalIdParamName, newValue); - externalId = newValue; - } - - LocalDate commencementDate = account.getProjectedCommencementDate(); - final String commencementDateParamName = "commencementDate"; - if (command.isChangeInLocalDateParameterNamed("commencementDate", commencementDate)) { - final LocalDate newValue = command.localDateValueOfParameterNamed(commencementDateParamName); - actualChanges.put(commencementDateParamName, newValue); - commencementDate = newValue; - } - - Money deposit = account.getDeposit(); - final String depositParamName = "deposit"; - if (command.isChangeInBigDecimalParameterNamed(depositParamName, deposit.getAmount())) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(depositParamName); - actualChanges.put(depositParamName, newValue); - actualChanges.put("locale", localeAsInput); - deposit = Money.of(deposit.getCurrency(), newValue); - } - - Integer tenureInMonths = account.getTenureInMonths(); - final String tenureInMonthsParamName = "tenureInMonths"; - if (command.isChangeInIntegerParameterNamed(tenureInMonthsParamName, tenureInMonths)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureInMonthsParamName); - actualChanges.put(tenureInMonthsParamName, newValue); - actualChanges.put("locale", localeAsInput); - tenureInMonths = newValue; - } - - BigDecimal maturityInterestRate = account.getInterestRate(); - final String maturityInterestRateParamName = "maturityInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(maturityInterestRateParamName, maturityInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(maturityInterestRateParamName); - actualChanges.put(maturityInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - maturityInterestRate = newValue; - } - - BigDecimal preClosureInterestRate = account.getPreClosureInterestRate(); - final String preClosureInterestRateParamName = "preClosureInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(preClosureInterestRateParamName, preClosureInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(preClosureInterestRateParamName); - actualChanges.put(preClosureInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - preClosureInterestRate = newValue; - } - - if (product.getMinInterestRate().compareTo(preClosureInterestRate) == -1) { throw new DepositAccounDataValidationtException( - preClosureInterestRate, product.getMinInterestRate()); } - - Integer interestCompoundedEvery = account.getInterestCompoundedEvery(); - final String interestCompoundedEveryParamName = "interestCompoundedEvery"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryParamName, interestCompoundedEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryParamName); - actualChanges.put(interestCompoundedEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestCompoundedEvery = newValue; - } - - PeriodFrequencyType interestCompoundedEveryPeriodType = account.getInterestCompoundedFrequencyType(); - final String interestCompoundedEveryPeriodTypeParamName = "interestCompoundedEveryPeriodType"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryPeriodTypeParamName, - interestCompoundedEveryPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryPeriodTypeParamName); - actualChanges.put(interestCompoundedEveryPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - interestCompoundedEveryPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - Boolean renewalAllowed = account.isRenewalAllowed(); - final String renewalAllowedParamName = "renewalAllowed"; - if (command.isChangeInBooleanParameterNamed(renewalAllowedParamName, renewalAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(renewalAllowedParamName); - actualChanges.put(renewalAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - renewalAllowed = newValue; - } - - Boolean preClosureAllowed = account.isPreClosureAllowed(); - final String preClosureAllowedParamName = "preClosureAllowed"; - if (command.isChangeInBooleanParameterNamed(preClosureAllowedParamName, preClosureAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(preClosureAllowedParamName); - actualChanges.put(preClosureAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - preClosureAllowed = newValue; - } - - Boolean isInterestWithdrawable = account.isInterestWithdrawable(); - final String isInterestWithdrawableParamName = "isInterestWithdrawable"; - if (command.isChangeInBooleanParameterNamed(isInterestWithdrawableParamName, isInterestWithdrawable)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isInterestWithdrawableParamName); - actualChanges.put(isInterestWithdrawableParamName, newValue); - actualChanges.put("locale", localeAsInput); - isInterestWithdrawable = newValue; - } - - Boolean isInterestCompoundingAllowed = account.isInterestCompoundingAllowed(); - final String isInterestCompoundingAllowedParamName = "interestCompoundingAllowed"; - if (command.isChangeInBooleanParameterNamed(isInterestCompoundingAllowedParamName, isInterestCompoundingAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isInterestCompoundingAllowedParamName); - actualChanges.put(isInterestCompoundingAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - isInterestCompoundingAllowed = newValue; - } - - Boolean isLockinPeriodAllowed = account.isLockinPeriodAllowed(); - final String isLockinPeriodAllowedParamName = "isLockinPeriodAllowed"; - if (command.isChangeInBooleanParameterNamed(isLockinPeriodAllowedParamName, isLockinPeriodAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isLockinPeriodAllowedParamName); - actualChanges.put(isLockinPeriodAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - isLockinPeriodAllowed = newValue; - } - - Integer lockinPeriod = account.getLockinPeriod(); - final String lockinPeriodParamName = "lockinPeriod"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodParamName, lockinPeriod)) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodParamName); - actualChanges.put(lockinPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - lockinPeriod = newValue; - } - - PeriodFrequencyType lockinPeriodType = account.getLockinPeriodType(); - final String lockinPeriodTypeParamName = "lockinPeriodType"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodTypeParamName, lockinPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodTypeParamName); - actualChanges.put(lockinPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - lockinPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - account.update(product, externalId, commencementDate, deposit, tenureInMonths, maturityInterestRate, preClosureInterestRate, - interestCompoundedEvery, interestCompoundedEveryPeriodType, renewalAllowed, preClosureAllowed, isInterestWithdrawable, - isInterestCompoundingAllowed, this.fixedTermDepositInterestCalculator, isLockinPeriodAllowed, lockinPeriod, - lockinPeriodType); - - return actualChanges; - } - - public Map updateApprovedDepositAccount(final DepositAccount account, final JsonCommand command) { - - final Map actualChanges = new LinkedHashMap(20); - final String localeAsInput = command.locale(); - - Boolean renewalAllowed = account.isRenewalAllowed(); - final String renewalAllowedParamName = "renewalAllowed"; - if (command.isChangeInBooleanParameterNamed(renewalAllowedParamName, renewalAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(renewalAllowedParamName); - actualChanges.put(renewalAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - renewalAllowed = newValue; - } - - Boolean isInterestWithdrawable = account.isInterestWithdrawable(); - final String isInterestWithdrawableParamName = "isInterestWithdrawable"; - if (command.isChangeInBooleanParameterNamed(isInterestWithdrawableParamName, isInterestWithdrawable)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isInterestWithdrawableParamName); - actualChanges.put(isInterestWithdrawableParamName, newValue); - actualChanges.put("locale", localeAsInput); - isInterestWithdrawable = newValue; - } - - account.update(renewalAllowed, isInterestWithdrawable); - - return actualChanges; - - } - - public void postInterest(final DepositAccount account) { - account.postInterestForDepositAccount(this.fixedTermDepositInterestCalculator); - } - - private Boolean isBooleanValueUpdated(final Boolean actualValue) { - Boolean isUpdated = false; - if (actualValue != null) { - isUpdated = true; - } - return isUpdated; - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountEnumerations.java deleted file mode 100644 index 0672c6a53..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountEnumerations.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountStatus; - -public class DepositAccountEnumerations { - - public static EnumOptionData status(final Integer statusId) { - return status(DepositAccountStatus.fromInt(statusId)); - } - - public static EnumOptionData status(final DepositAccountStatus status) { - EnumOptionData optionData = null; - switch (status) { - 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"); - break; - /* - * case APPROVED: optionData = new - * EnumOptionData(DepositAccountStatus - * .APPROVED.getValue().longValue(), - * DepositAccountStatus.APPROVED.getCode(), "Approved"); break; - */ - case ACTIVE: - optionData = new EnumOptionData(DepositAccountStatus.ACTIVE.getValue().longValue(), DepositAccountStatus.ACTIVE.getCode(), - "Active"); - break; - case REJECTED: - optionData = new EnumOptionData(DepositAccountStatus.REJECTED.getValue().longValue(), - DepositAccountStatus.REJECTED.getCode(), "Rejected"); - break; - case WITHDRAWN_BY_CLIENT: - optionData = new EnumOptionData(DepositAccountStatus.WITHDRAWN_BY_CLIENT.getValue().longValue(), - DepositAccountStatus.WITHDRAWN_BY_CLIENT.getCode(), "Withdrawn by applicant"); - break; - case MATURED: - optionData = new EnumOptionData(DepositAccountStatus.MATURED.getValue().longValue(), - DepositAccountStatus.MATURED.getCode(), "Matured"); - break; - case CLOSED: - optionData = new EnumOptionData(DepositAccountStatus.CLOSED.getValue().longValue(), DepositAccountStatus.CLOSED.getCode(), - "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; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformService.java deleted file mode 100644 index 0e49ba4eb..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformService.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.math.BigDecimal; -import java.util.Collection; - -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountData; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountsForLookup; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositPermissionData; - -public interface DepositAccountReadPlatformService { - - Collection retrieveAllDepositAccounts(); - - DepositAccountData retrieveDepositAccount(Long accountId); - - DepositAccountData retrieveNewDepositAccountDetails(Long clientId, Long productId); - - DepositPermissionData retrieveDepositAccountsPermissions(DepositAccountData depositAccountData); - - BigDecimal retrieveAvailableInterestForWithdrawal(DepositAccountData account); - - Collection retrieveDepositAccountForLookup(); -} - diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformServiceImpl.java deleted file mode 100644 index 238e718f7..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountReadPlatformServiceImpl.java +++ /dev/null @@ -1,326 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; - -import org.joda.time.LocalDate; -import org.joda.time.Months; -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.domain.JdbcSupport; -import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.client.data.ClientData; -import org.mifosplatform.portfolio.client.service.ClientReadPlatformService; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingsDepositEnumerations; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountData; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountTransactionData; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountsForLookup; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositPermissionData; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccountNotFoundException; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductData; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductLookup; -import org.mifosplatform.portfolio.savingsdepositproduct.service.DepositProductReadPlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Service; - -@Service -public class DepositAccountReadPlatformServiceImpl implements DepositAccountReadPlatformService { - - private final PlatformSecurityContext context; - private final JdbcTemplate jdbcTemplate; - private final DepositProductReadPlatformService depositProductReadPlatformService; - private final ClientReadPlatformService clientReadPlatformService; - - @Autowired - public DepositAccountReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource, - final DepositProductReadPlatformService depositProductReadPlatformService, - final ClientReadPlatformService clientReadPlatformService) { - this.context = context; - jdbcTemplate = new JdbcTemplate(dataSource); - this.depositProductReadPlatformService = depositProductReadPlatformService; - this.clientReadPlatformService = clientReadPlatformService; - } - - @Override - public Collection retrieveAllDepositAccounts() { - - this.context.authenticatedUser(); - - DepositAccountMapper mapper = new DepositAccountMapper(); - - String sql = "select " + mapper.schema() + " where da.is_deleted=0"; - - return this.jdbcTemplate.query(sql, mapper, new Object[] {}); - } - - @Override - public DepositAccountData retrieveDepositAccount(final Long accountId) { - try { - DepositAccountMapper mapper = new DepositAccountMapper(); - - String sql = "select " + mapper.schema() + " where da.id = ? and da.is_deleted=0"; - - DepositAccountData depositAccountData = this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { accountId }); - - // FIXME - kw - the call to find transactions for deposit account to - // add to the deposit account payload can be decided at the api - // level - // depending on whether the requester wants them or not instead of - // always getting the transactions - DepositAccountTransactionMapper transactionMapper = new DepositAccountTransactionMapper(); - String transactionSchema = "select " + transactionMapper.schema() + " where txn.deposit_account_id = ? "; - - Collection depositAccountTransactions = this.jdbcTemplate.query(transactionSchema, - transactionMapper, new Object[] { accountId }); - if (!depositAccountTransactions.isEmpty()) { - DepositPermissionData permissions = null; - depositAccountData = new DepositAccountData(depositAccountData, permissions, depositAccountTransactions); - } - - return depositAccountData; - } catch (EmptyResultDataAccessException e) { - throw new DepositAccountNotFoundException(accountId); - } - } - - @Override - public DepositAccountData retrieveNewDepositAccountDetails(final Long clientId, final Long productId) { - - context.authenticatedUser(); - - ClientData clientAccount = this.clientReadPlatformService.retrieveIndividualClient(clientId); - - DepositAccountData accountData = null; - - Collection depositProducts = this.depositProductReadPlatformService.retrieveAllDepositProductsForLookup(); - - if (productId != null) { - DepositProductData selectedProduct = findDepositProductById(depositProducts, productId); - - CurrencyData currency = new CurrencyData(selectedProduct.getCurrencyCode(), "", selectedProduct.getDigitsAfterDecimal(), "", ""); - - accountData = new DepositAccountData(clientAccount.id(), clientAccount.displayName(), selectedProduct.getId(), - selectedProduct.getName(), currency, selectedProduct.getMinimumBalance(), - selectedProduct.getMaturityDefaultInterestRate(), selectedProduct.getTenureInMonths(), - selectedProduct.getInterestCompoundedEvery(), selectedProduct.getInterestCompoundedEveryPeriodType(), - selectedProduct.isRenewalAllowed(), selectedProduct.isPreClosureAllowed(), selectedProduct.getPreClosureInterestRate(), - selectedProduct.isInterestCompoundingAllowed(),selectedProduct.getLockinPeriod(),selectedProduct.getLockinPeriodType(),selectedProduct.isLockinPeriodAllowed()); - } else { - accountData = DepositAccountData.createFrom(clientAccount.id(), clientAccount.displayName()); - } - - return accountData; - } - - private DepositProductData findDepositProductById(final Collection depositProducts, final Long productId) { - DepositProductData match = this.depositProductReadPlatformService.retrieveNewDepositProductDetails(); - for (DepositProductLookup depositProductLookup : depositProducts) { - if (depositProductLookup.hasId(productId)) { - match = this.depositProductReadPlatformService.retrieveDepositProductData(depositProductLookup.id()); - break; - } - } - return match; - } - - private static final class DepositAccountMapper implements RowMapper { - - public String schema() { - return "da.id as id, da.external_id as externalId, da.client_id as clientId, da.product_id as productId, " - + " da.currency_code as currencyCode, da.currency_digits as currencyDigits, " - + " da.deposit_amount as depositAmount, da.status_enum as statusId, " - + " da.maturity_nominal_interest_rate as interestRate, da.tenure_months as termInMonths, da.projected_commencement_date as projectedCommencementDate," - + " da.actual_commencement_date as actualCommencementDate, da.matures_on_date as maturedOn," - + " da.projected_interest_accrued_on_maturity as projectedInterestAccrued, da.actual_interest_accrued as actualInterestAccrued, " - + " da.projected_total_maturity_amount as projectedMaturityAmount, da.actual_total_amount as actualMaturityAmount, " - + " da.interest_compounded_every as interestCompoundedEvery, da.interest_compounded_every_period_enum as interestCompoundedEveryPeriodType, " - + " da.is_renewal_allowed as renewalAllowed, da.is_preclosure_allowed as preClosureAllowed, da.pre_closure_interest_rate as preClosureInterestRate, " - + " da.withdrawnon_date as withdrawnonDate, da.rejectedon_date as rejectedonDate, da.closedon_date as closedonDate, " - + " da.interest_paid as interestPaid, da.is_interest_withdrawable as isInterestWithdrawable, da.is_compounding_interest_allowed as interestCompoundingAllowed, " - + " da.is_lock_in_period_allowed as isLockinPeriodAllowed, da.lock_in_period as lockinPeriod, da.lock_in_period_type lockinPeriodType, " - + " da.available_interest as availableInterest, da.interest_posted_amount as interestPostedAmount, da.last_interest_posted_date as lastInterestPostedDate, da.next_interest_posting_date as nextInterestPostedDate," - + " c.firstname as firstname, c.lastname as lastname, pd.name as productName, c.image_key as imageKey, " - + " curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol, " - + " ecd.father_name as fatherName, ecd.client_address as clientAddress " + " from m_deposit_account da " - + " join m_currency curr on curr.code = da.currency_code " + " join m_client c on c.id = da.client_id " - + " join m_product_deposit pd on pd.id = da.product_id" - + " left join extra_client_details_hugo_specific ecd on da.client_id = ecd.client_id "; - } - - @Override - public DepositAccountData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - - Long id = rs.getLong("id"); - String externalId = rs.getString("externalId"); - Long clientId = rs.getLong("clientId"); - String clientName = rs.getString("firstname") + " " + rs.getString("lastname"); - Long productId = rs.getLong("productId"); - String productName = rs.getString("productName"); - - Integer statusId = JdbcSupport.getInteger(rs, "statusId"); - EnumOptionData status = DepositAccountEnumerations.status(statusId); - - String currencyCode = rs.getString("currencyCode"); - String currencyName = rs.getString("currencyName"); - String currencyNameCode = rs.getString("currencyNameCode"); - String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); - Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); - CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, - currencyNameCode); - - BigDecimal depositAmount = rs.getBigDecimal("depositAmount"); - BigDecimal interestRate = rs.getBigDecimal("interestRate"); - - Integer termInMonths = JdbcSupport.getInteger(rs, "termInMonths"); - - LocalDate projectedCommencementDate = JdbcSupport.getLocalDate(rs, "projectedCommencementDate"); - LocalDate actualCommencementDate = JdbcSupport.getLocalDate(rs, "actualCommencementDate"); - LocalDate maturedOn = JdbcSupport.getLocalDate(rs, "maturedOn"); - BigDecimal projectedInterestAccrued = rs.getBigDecimal("projectedInterestAccrued"); - BigDecimal actualInterestAccrued = rs.getBigDecimal("actualInterestAccrued"); - - BigDecimal projectedMaturityAmount = rs.getBigDecimal("projectedMaturityAmount"); - BigDecimal actualMaturityAmount = rs.getBigDecimal("actualMaturityAmount"); - - Integer interestCompoundedEvery = JdbcSupport.getInteger(rs, "interestCompoundedEvery"); - Integer interestCompoundedEveryPeriodTypeValue = JdbcSupport.getInteger(rs, "interestCompoundedEveryPeriodType"); - EnumOptionData interestCompoundedEveryPeriodType = SavingsDepositEnumerations - .interestCompoundingPeriodType(interestCompoundedEveryPeriodTypeValue); - - boolean renewalAllowed = rs.getBoolean("renewalAllowed"); - boolean preClosureAllowed = rs.getBoolean("preClosureAllowed"); - boolean interestCompoundingAllowed = rs.getBoolean("interestCompoundingAllowed"); - - BigDecimal preClosureInterestRate = rs.getBigDecimal("preClosureInterestRate"); - - LocalDate withdrawnonDate = JdbcSupport.getLocalDate(rs, "withdrawnonDate"); - LocalDate rejectedonDate = JdbcSupport.getLocalDate(rs, "rejectedonDate"); - LocalDate closedonDate = JdbcSupport.getLocalDate(rs, "closedonDate"); - - boolean isInterestWithdrawable = rs.getBoolean("isInterestWithdrawable"); - BigDecimal interestPaid = rs.getBigDecimal("interestPaid"); - - boolean isLockinPeriodAllowed = rs.getBoolean("isLockinPeriodAllowed"); - Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod"); - Integer lockinPeriodTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodType"); - EnumOptionData lockinPeriodType = SavingsDepositEnumerations.interestCompoundingPeriodType(lockinPeriodTypeValue); - - BigDecimal availableInterest = rs.getBigDecimal("availableInterest"); - BigDecimal interestPostedAmount = rs.getBigDecimal("interestPostedAmount"); - LocalDate lastInterestPostedDate = JdbcSupport.getLocalDate(rs, "lastInterestPostedDate"); - LocalDate nextInterestPostedDate = JdbcSupport.getLocalDate(rs, "nextInterestPostedDate"); - String imageKey = rs.getString("imageKey"); - String fatherName = rs.getString("fatherName"); - String address = rs.getString("clientAddress"); - - return new DepositAccountData(id, externalId, status, clientId, clientName, productId, productName, currencyData, - depositAmount, interestRate, termInMonths, projectedCommencementDate, actualCommencementDate, maturedOn, - projectedInterestAccrued, actualInterestAccrued, projectedMaturityAmount, actualMaturityAmount, - interestCompoundedEvery, interestCompoundedEveryPeriodType, renewalAllowed, preClosureAllowed, preClosureInterestRate, - withdrawnonDate, rejectedonDate, closedonDate, isInterestWithdrawable, interestPaid, interestCompoundingAllowed, - isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, availableInterest, interestPostedAmount, lastInterestPostedDate, - nextInterestPostedDate, fatherName, address, imageKey); - } - } - - private static final class DepositAccountTransactionMapper implements RowMapper { - - public String schema() { - return " txn.id as transactionId, txn.deposit_account_id as accountId, txn.transaction_type_enum as transactionType, txn.transaction_date as transactionDate, txn.amount as transactionAmount, txn.interest as interestAmount, " - + "txn.total as total from m_deposit_account_transaction txn"; - } - - @Override - public DepositAccountTransactionData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - - Long transactionId = rs.getLong("transactionId"); - Long accountId = rs.getLong("accountId"); - Integer transactionTypeValue = JdbcSupport.getInteger(rs, "transactionType"); - EnumOptionData transactionType = DepositAccountTransactionEnumerations.depositType(transactionTypeValue); - LocalDate transactionDate = JdbcSupport.getLocalDate(rs, "transactionDate"); - BigDecimal transactionAmount = rs.getBigDecimal("transactionAmount"); - BigDecimal interestAmount = rs.getBigDecimal("interestAmount"); - BigDecimal total = rs.getBigDecimal("total"); - - return new DepositAccountTransactionData(transactionId, accountId, transactionType, transactionDate, transactionAmount, - interestAmount, total); - } - - } - - @Override - public DepositPermissionData retrieveDepositAccountsPermissions(DepositAccountData depositAccountData) { - boolean pendingApproval = (depositAccountData.getStatus().getId().equals(100L)); - boolean undoApprovalAllowed = (depositAccountData.getStatus().getId().equals(300L)); - boolean renewelAllowed = false; - if (depositAccountData.getMaturedOn() != null) { - if (new LocalDate().isAfter(depositAccountData.getMaturedOn())/* - * || - * depositAccountData - * . - * getMaturedOn - * (). - * isEqual - * ( - * new - * LocalDate - * ()) - */) { - renewelAllowed = depositAccountData.isRenewalAllowed(); - } - } - boolean rejectAllowed = pendingApproval; - boolean withdrawnByApplicantAllowed = pendingApproval; - boolean interestWithdrawAllowed = depositAccountData.isInterestWithdrawable(); - boolean isMaturedDepositAccount = (depositAccountData.getStatus().getId().equals(700L)); - - return new DepositPermissionData(rejectAllowed, withdrawnByApplicantAllowed, undoApprovalAllowed, pendingApproval, - interestWithdrawAllowed, renewelAllowed, isMaturedDepositAccount); - } - - @Override - public BigDecimal retrieveAvailableInterestForWithdrawal(DepositAccountData account) { - BigDecimal interstGettingForPeriod = BigDecimal.valueOf(account.getActualInterestAccrued().doubleValue() - / new Double(account.getTenureInMonths())); - Integer noOfMonthsforInterestCal = Months.monthsBetween(account.getActualCommencementDate(), new LocalDate()).getMonths(); - Integer noOfPeriods = noOfMonthsforInterestCal / account.getInterestCompoundedEvery(); - return BigDecimal.valueOf(interstGettingForPeriod.multiply(new BigDecimal(noOfPeriods)).doubleValue() - - account.getInterestPaid().doubleValue()); - } - - @Override - public Collection retrieveDepositAccountForLookup() { - - this.context.authenticatedUser(); - DepositAccountLookupMapper mapper = new DepositAccountLookupMapper(); - String sql = "select " + mapper.depositAccountLookupSchema(); - return this.jdbcTemplate.query(sql, mapper, new Object[] {}); - - } - - private static final class DepositAccountLookupMapper implements RowMapper { - - public String depositAccountLookupSchema() { - return " da.id as id from m_deposit_account da where da.status_enum=300 and da.is_deleted=0"; - } - - @Override - public DepositAccountsForLookup mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - Long id = rs.getLong("id"); - return new DepositAccountsForLookup(id); - } - - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountTransactionEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountTransactionEnumerations.java deleted file mode 100644 index 42c732b94..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountTransactionEnumerations.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountTransactionType; - -public class DepositAccountTransactionEnumerations { - - public static EnumOptionData depositType(final Integer statusId) { - return depositType(DepositAccountTransactionType.fromInt(statusId)); - } - - private static EnumOptionData depositType(DepositAccountTransactionType transactionType) { - - EnumOptionData optionData = null; - switch (transactionType) { - case DEPOSIT: - optionData = new EnumOptionData(DepositAccountTransactionType.DEPOSIT.getValue().longValue(), - DepositAccountTransactionType.DEPOSIT.getCode(), "Deposit"); - break; - - case WITHDRAW: - optionData = new EnumOptionData(DepositAccountTransactionType.WITHDRAW.getValue().longValue(), - DepositAccountTransactionType.WITHDRAW.getCode(), "Withdraw"); - break; - - case REVERSAL: - optionData = new EnumOptionData(DepositAccountTransactionType.REVERSAL.getValue().longValue(), - DepositAccountTransactionType.REVERSAL.getCode(), "Revarsal"); - break; - - case INTEREST_POSTING: - optionData=new EnumOptionData(DepositAccountTransactionType.INTEREST_POSTING.getValue().longValue(), DepositAccountTransactionType.INTEREST_POSTING.getCode(), "Interest posting"); - break; - - default: - optionData = new EnumOptionData(DepositAccountTransactionType.INVALID.getValue().longValue(), - DepositAccountTransactionType.INVALID.getCode(), "Invalid Transaction"); - break; - } - return optionData; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformService.java deleted file mode 100644 index 23d9595ba..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformService.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.util.Collection; - -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountsForLookup; - -public interface DepositAccountWritePlatformService { - - CommandProcessingResult createDepositAccount(JsonCommand command); - - CommandProcessingResult updateDepositAccount(Long accountId, JsonCommand command); - - CommandProcessingResult deleteDepositAccount(Long entityId); - - CommandProcessingResult approveDepositApplication(JsonCommand command); - - CommandProcessingResult rejectDepositApplication(JsonCommand command); - - CommandProcessingResult withdrawDepositApplication(JsonCommand command); - - CommandProcessingResult undoDepositApproval(JsonCommand undoCommand); - - CommandProcessingResult withdrawDepositAccountMoney(JsonCommand command); - - CommandProcessingResult withdrawDepositAccountInterestMoney(JsonCommand command); - - CommandProcessingResult renewDepositAccount(JsonCommand command); - - CommandProcessingResult postInterestToDepositAccount(Collection accounts); - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java deleted file mode 100644 index 05df1130f..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java +++ /dev/null @@ -1,405 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; -import org.mifosplatform.infrastructure.security.exception.NoAuthorizationException; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.portfolio.note.domain.Note; -import org.mifosplatform.portfolio.note.domain.NoteRepository; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountsForLookup; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccount; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountRepository; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositAccountStatus; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachine; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.DepositLifecycleStateMachineImpl; -import org.mifosplatform.portfolio.savingsdepositaccount.domain.FixedTermDepositInterestCalculator; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccountNotFoundException; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccountReopenException; -import org.mifosplatform.portfolio.savingsdepositaccount.exception.DepositAccountTransactionsException; -import org.mifosplatform.portfolio.savingsdepositaccount.serialization.DepositAccountCommandFromApiJsonDeserializer; -import org.mifosplatform.portfolio.savingsdepositaccount.serialization.DepositAccountStateTransitionCommandFromApiJsonDeserializer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements DepositAccountWritePlatformService { - - private final static Logger logger = LoggerFactory.getLogger(DepositAccountWritePlatformServiceJpaRepositoryImpl.class); - - private final PlatformSecurityContext context; - private final DepositAccountRepository depositAccountRepository; - private final DepositAccountAssembler depositAccountAssembler; - private final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator; - private final NoteRepository noteRepository; - private final DepositAccountCommandFromApiJsonDeserializer fromApiJsonDeserializer; - private final DepositAccountStateTransitionCommandFromApiJsonDeserializer depositAccountStateTransitionCommandFromApiJsonDeserializer; - - @Autowired - public DepositAccountWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final DepositAccountRepository depositAccountRepository, final DepositAccountAssembler depositAccountAssembler, - final FixedTermDepositInterestCalculator fixedTermDepositInterestCalculator, final NoteRepository noteRepository, - final DepositAccountCommandFromApiJsonDeserializer fromApiJsonDeserializer, - final DepositAccountStateTransitionCommandFromApiJsonDeserializer depositAccountStateTransitionCommandFromApiJsonDeserializer) { - this.context = context; - this.depositAccountRepository = depositAccountRepository; - this.depositAccountAssembler = depositAccountAssembler; - this.fixedTermDepositInterestCalculator = fixedTermDepositInterestCalculator; - this.noteRepository = noteRepository; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; - this.depositAccountStateTransitionCommandFromApiJsonDeserializer = depositAccountStateTransitionCommandFromApiJsonDeserializer; - } - - /* - * Guaranteed to throw an exception no matter what the data integrity issue - * is. - */ - private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - - Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("deposit_acc_external_id")) { - final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException( - "error.msg.desposit.account.duplicate.externalId", "Deposit account with externalId " + externalId - + " already exists", "externalId", externalId); } - - logger.error(dve.getMessage(), dve); - throw new PlatformDataIntegrityException("error.msg.deposit.account.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } - - @Transactional - @Override - public CommandProcessingResult createDepositAccount(final JsonCommand command) { - - try { - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForCreate(command.json()); - - final DepositAccount account = this.depositAccountAssembler.assembleFrom(command); - this.depositAccountRepository.save(account); - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return new CommandProcessingResult(Long.valueOf(-1)); - } - } - - @Transactional - @Override - public CommandProcessingResult deleteDepositAccount(final Long accountId) { - - this.context.authenticatedUser(); - - DepositAccount account = this.depositAccountRepository.findOne(accountId); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(accountId); } - - account.delete(); - this.depositAccountRepository.save(account); - - return new CommandProcessingResultBuilder() // - .withEntityId(accountId) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult approveDepositApplication(final JsonCommand command) { - - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForApprove(command.json()); - - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - - final LocalDate commencementDate = command.localDateValueOfParameterNamed("commencementDate"); - - Map actualChanges = account.approve(commencementDate, defaultDepositLifecycleStateMachine(), command, this.fixedTermDepositInterestCalculator); - - this.depositAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.depositNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .with(actualChanges) - .build(); - - } - - private boolean isBeforeToday(final LocalDate date) { - return date.isBefore(new LocalDate()); - } - private DepositLifecycleStateMachine defaultDepositLifecycleStateMachine() { - List allowedDepositStatuses = Arrays.asList(DepositAccountStatus.values()); - return new DepositLifecycleStateMachineImpl(allowedDepositStatuses); - } - - @Transactional - @Override - public CommandProcessingResult rejectDepositApplication(JsonCommand command) { - - this.context.authenticatedUser(); - this.depositAccountStateTransitionCommandFromApiJsonDeserializer.validateForReject(command.json()); - - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - - LocalDate eventDate = command.localDateValueOfParameterNamed("eventDate"); - if (this.isBeforeToday(eventDate)) { - throw new NoAuthorizationException("User has no authority to reject deposit with a date in the past."); - } - - account.reject(eventDate, defaultDepositLifecycleStateMachine()); - this.depositAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.depositNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult withdrawDepositApplication(JsonCommand command) { - - this.context.authenticatedUser(); - this.depositAccountStateTransitionCommandFromApiJsonDeserializer.validateForWithdrawDepositApplication(command.json()); - - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - - LocalDate eventDate = command.localDateValueOfParameterNamed("eventDate"); - if (this.isBeforeToday(eventDate)) { - throw new NoAuthorizationException("User has no authority to withdraw deposit application with a date in the past."); - } - - account.withdrawnByApplicant(eventDate, defaultDepositLifecycleStateMachine()); - this.depositAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.depositNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult undoDepositApproval(JsonCommand command) { - - context.authenticatedUser(); - - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - - account.undoDepositApproval(defaultDepositLifecycleStateMachine()); - this.depositAccountRepository.save(account); - - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.depositNote(account, noteText); - this.noteRepository.save(note); - } - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult withdrawDepositAccountMoney(final JsonCommand command) { - - this.context.authenticatedUser(); - this.depositAccountStateTransitionCommandFromApiJsonDeserializer.validateForWithdrawDepositAmount(command.json()); - - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - - LocalDate eventDate = command.localDateValueOfParameterNamed("maturesOnDate"); - - Integer lockinPeriod = account.getLockinPeriod(); - LocalDate lockinPeriodExpDate = account.getActualCommencementDate().plusMonths(Integer.valueOf(lockinPeriod)); - if (account.isLockinPeriodAllowed()) { - if (eventDate.isBefore(lockinPeriodExpDate)) { throw new DepositAccountTransactionsException( - "deposit.transaction.canot.withdraw.before.lockinperiod.reached", - "You can not withdraw your application before maturity date reached"); } - } - // if (eventDate.isBefore(account.maturesOnDate())) { - // this.depositAccountAssembler.adjustTotalAmountForPreclosureInterest(account, - // eventDate); - // } - account.withdrawDepositAccountMoney(defaultDepositLifecycleStateMachine(), fixedTermDepositInterestCalculator, eventDate); - this.depositAccountRepository.save(account); - String noteText = command.stringValueOfParameterNamed("note"); - if (StringUtils.isNotBlank(noteText)) { - Note note = Note.depositNote(account, noteText); - this.noteRepository.save(note); - } - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult withdrawDepositAccountInterestMoney(JsonCommand command) { - - context.authenticatedUser(); - this.depositAccountStateTransitionCommandFromApiJsonDeserializer.validateForWithdrawInterestAmount(command.json()); - - BigDecimal interestAmount = command.bigDecimalValueOfParameterNamed("amount"); - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - if (account.isInterestWithdrawable() && !account.isInterestCompoundingAllowed()) { - - // BigDecimal totalAvailableInterestForWithdrawal = getTotalWithdrawableInterestAvailable(account); - // BigDecimal interestPaid = account.getInterstPaid(); - BigDecimal remainInterestForWithdrawal = account.getAvailableInterest(); //totalAvailableInterestForWithdrawal.subtract(interestPaid); - - if (remainInterestForWithdrawal.doubleValue() > 0) { - if (remainInterestForWithdrawal.doubleValue() >= interestAmount.doubleValue() - && interestAmount.doubleValue() > 0) { - account.withdrawInterest(Money.of(account.getDeposit().getCurrency(), interestAmount)); - this.depositAccountRepository.save(account); - } else { - throw new DepositAccountTransactionsException("deposit.transaction.interest.withdrawal.exceed", "You can Withdraw " - + remainInterestForWithdrawal + " only"); - } - } else { - throw new DepositAccountTransactionsException("deposit.transaction.interest.withdrawal.insufficient.amount", - "You don't have enough money for withdrawal"); - } - } else { - throw new DepositAccountTransactionsException("deposit.transaction.interest.withdrawal.cannot.withdraw", - "You can not withdraw interst for this account"); - } - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .build(); - } - - @Transactional - @Override - public CommandProcessingResult renewDepositAccount(JsonCommand command) { - - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForRenew(command.json()); - - DepositAccount account = this.depositAccountRepository.findOne(command.entityId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(command.entityId()); } - - // FIXME - KW - extract whats in this if into a method that naturally - // describes what you are checking. - if (account.isRenewalAllowed() - && (new LocalDate().isAfter(account.maturesOnDate()) || new LocalDate().isEqual(account.maturesOnDate()))) { - - if (account.isActive()) { - final Map changes = new LinkedHashMap(20); - final DepositAccount renewedAccount = this.depositAccountAssembler.assembleFrom(account, command,changes); - this.depositAccountRepository.save(renewedAccount); - account.closeDepositAccount(defaultDepositLifecycleStateMachine()); - this.depositAccountRepository.save(account); - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .with(changes) - .build(); - } - - throw new DepositAccountReopenException(account.getMaturityDate()); - } - - throw new DepositAccountReopenException(account.getMaturityDate()); - } - - @Transactional - @Override - public CommandProcessingResult updateDepositAccount(Long accountId, JsonCommand command) { - - try { - - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForUpdate(command.json()); - - Map changes = new LinkedHashMap(20); - - final DepositAccount account = this.depositAccountRepository.findOne(accountId); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(accountId); } - - if (account.isSubmittedAndPendingApproval()) { - changes = this.depositAccountAssembler.assembleUpdatedDepositAccount(account, command); - } else if (account.isActive()) { - changes = this.depositAccountAssembler.updateApprovedDepositAccount(account, command); - } - - this.depositAccountRepository.save(account); - - return new CommandProcessingResultBuilder() // - .withEntityId(account.getId()) // - .with(changes) - .build(); - - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return new CommandProcessingResult(Long.valueOf(-1)); - } - } - - @Transactional - @Override - public CommandProcessingResult postInterestToDepositAccount(Collection accounts) { - - try { - - for (DepositAccountsForLookup accountData : accounts) { - DepositAccount account = this.depositAccountRepository.findOne(accountData.getId()); - if (account == null || account.isDeleted()) { throw new DepositAccountNotFoundException(accountData.getId()); } - this.depositAccountAssembler.postInterest(account); - this.depositAccountRepository.save(account); - } - return new CommandProcessingResultBuilder() // - .withEntityId(Long.valueOf(accounts.size())) // - .build(); - } catch (Exception e) { - return new CommandProcessingResult(Long.valueOf(-1)); - } - - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositStateTransitionCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositStateTransitionCommandValidator.java deleted file mode 100644 index 04004d292..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/DepositStateTransitionCommandValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositStateTransitionCommand; - -public class DepositStateTransitionCommandValidator { - - private final DepositStateTransitionCommand command; - - public DepositStateTransitionCommandValidator(final DepositStateTransitionCommand command) { - this.command = command; - } - - public void validate() { - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.transition"); - baseDataValidator.reset().parameter("accountId").value(command.getAccountId()).notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter("eventDate").value(command.getEventDate()).notNull(); - baseDataValidator.reset().parameter("note").value(command.getNote()).notNull(); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/GeneratePDF.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/GeneratePDF.java deleted file mode 100644 index 3e4895845..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/GeneratePDF.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.io.File; -import java.io.FileOutputStream; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; - -import org.mifosplatform.infrastructure.core.service.FileUtils; -import org.mifosplatform.portfolio.savingsdepositaccount.data.DepositAccountData; - -import com.lowagie.text.Document; -import com.lowagie.text.Element; -import com.lowagie.text.Font; -import com.lowagie.text.FontFactory; -import com.lowagie.text.Image; -import com.lowagie.text.Paragraph; -import com.lowagie.text.pdf.CMYKColor; -import com.lowagie.text.pdf.PdfWriter; - -public class GeneratePDF { - - private final DepositAccountData account; - - public GeneratePDF(DepositAccountData account) { - this.account = account; - } - - public String generatePDF() { - - String fileLocation = FileUtils.MIFOSX_BASE_DIR + File.separator+ "Print_FD_Details"; - - /** Recursively create the directory if it does not exist **/ - if (!new File(fileLocation).isDirectory()) { - new File(fileLocation).mkdirs(); - } - String printFDdetailsLocation = fileLocation + File.separator + account.getId() + ".pdf"; - SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy"); - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - - try { - Document document = new Document(); - PdfWriter.getInstance(document, new FileOutputStream(printFDdetailsLocation)); - document.open(); - - Paragraph paragraph = new Paragraph("FIXED DEPOSIT CERTIFICATE ", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 255, 0, 0))); - - paragraph.setAlignment(Element.ALIGN_CENTER); - paragraph.setSpacingAfter(30); - - document.add(paragraph); - Image img = Image.getInstance(account.getImageKey()); - img.scaleAbsolute(70, 80); - img.setAbsolutePosition(450, 670); - document.add(img); - Font font = FontFactory.getFont(FontFactory.COURIER, 10); - document.add(new Paragraph("Extenal id: "+ account.getExternalId(), font)); - document.add(new Paragraph("Created date: "+ dateFormat.format(account.getActualCommencementDate().toDate()), font)); - document.add(new Paragraph("Mature date: " + dateFormat.format(account.getMaturedOn().toDate()), font)); - document.add(new Paragraph("Client name: " + account.getClientName(), font)); - document.add(new Paragraph("Amount: " + decimalFormat.format(account.getDeposit()), font)); - document.add(new Paragraph("FD interest rate: " + decimalFormat.format(account.getMaturityInterestRate()), font)); - document.add(new Paragraph("Preclosure interest rate: " + decimalFormat.format(account.getPreClosureInterestRate()), font)); - document.add(new Paragraph("Tenure: " + account.getTenureInMonths(), font)); - document.add(new Paragraph("Maturity Amount: " + decimalFormat.format(account.getActualMaturityAmount()), font)); - document.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - return printFDdetailsLocation; - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/RenewDepositAccountCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/RenewDepositAccountCommandValidator.java deleted file mode 100644 index 9132a5a91..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositaccount/service/RenewDepositAccountCommandValidator.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositaccount.service; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.portfolio.savingsdepositaccount.command.DepositAccountCommand; - -public class RenewDepositAccountCommandValidator { - - private final DepositAccountCommand command; - - public RenewDepositAccountCommandValidator(final DepositAccountCommand command) { - this.command = command; - } - - public void validateForCreate() { - - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.account"); - - baseDataValidator.reset().parameter("clientId").value(command.getClientId()).ignoreIfNull(); - baseDataValidator.reset().parameter("productId").value(command.getProductId()).ignoreIfNull(); - baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100); - - baseDataValidator.reset().parameter("deposit").value(command.getDepositAmount()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityInterestRate").value(command.getMaturityInterestRate()).ignoreIfNull() - .zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).ignoreIfNull() - .zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).ignoreIfNull().integerGreaterThanZero(); - - baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull() - .integerGreaterThanZero(); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()) - .ignoreIfNull().inMinMaxRange(2, 2); - baseDataValidator.reset().parameter("commencementDate").value(command.getCommencementDate()).ignoreIfNull(); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/command/DepositProductCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/command/DepositProductCommand.java deleted file mode 100644 index b87cfa599..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/command/DepositProductCommand.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.command; - -import java.math.BigDecimal; -import java.util.Set; - -public class DepositProductCommand { - - private final Long id; - private final String externalId; - private final String name; - private final String description; - - private final String currencyCode; - private final Integer digitsAfterDecimal; - - private final BigDecimal minimumBalance; - private final BigDecimal maximumBalance; - - private final Integer tenureInMonths; - private final BigDecimal maturityDefaultInterestRate; - private final BigDecimal maturityMinInterestRate; - private final BigDecimal maturityMaxInterestRate; - private final Integer interestCompoundedEvery; - private final Integer interestCompoundedEveryPeriodType; - private final boolean isLockinPeriodAllowed; - private final Integer lockinPeriod; - private final Integer lockinPeriodType; - - private final boolean renewalAllowed; - private final boolean preClosureAllowed; - private final BigDecimal preClosureInterestRate; - - private final boolean interestCompoundingAllowed; - - private final Set modifiedParameters; - - public DepositProductCommand(final Set modifiedParameters, final Long id, final String externalId, final String name, - final String description, final String currencyCode, final Integer digitsAfterDecimal, final BigDecimal minimumBalance, - final BigDecimal maximumBalance, final Integer tenureInMonths, final BigDecimal maturityDefaultInterestRate, - final BigDecimal maturityMinInterestRate, final BigDecimal maturityMaxInterestRate, final Integer interestCompoundedEvery, - final Integer interestCompoundedEveryPeriodType, final boolean renewalAllowed, final boolean preClosureAllowed, - final BigDecimal preClosureInterestRate, final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final Integer lockinPeriodType) { - this.id = id; - this.externalId = externalId; - this.name = name; - this.description = description; - - this.currencyCode = currencyCode; - this.digitsAfterDecimal = digitsAfterDecimal; - - this.minimumBalance = minimumBalance; - this.maximumBalance = maximumBalance; - - this.tenureInMonths = tenureInMonths; - this.maturityDefaultInterestRate = maturityDefaultInterestRate; - this.maturityMinInterestRate = maturityMinInterestRate; - this.maturityMaxInterestRate = maturityMaxInterestRate; - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType; - this.preClosureInterestRate = preClosureInterestRate; - - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - this.interestCompoundingAllowed = interestCompoundingAllowed; - - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - - this.modifiedParameters = modifiedParameters; - - } - - public Long getId() { - return id; - } - - public String getExternalId() { - return externalId; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public String getCurrencyCode() { - return currencyCode; - } - - public Integer getDigitsAfterDecimal() { - return digitsAfterDecimal; - } - - public BigDecimal getMinimumBalance() { - return minimumBalance; - } - - public BigDecimal getMaximumBalance() { - return maximumBalance; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public BigDecimal getMaturityDefaultInterestRate() { - return maturityDefaultInterestRate; - } - - public BigDecimal getMaturityMinInterestRate() { - return maturityMinInterestRate; - } - - public BigDecimal getMaturityMaxInterestRate() { - return maturityMaxInterestRate; - } - - public Integer getInterestCompoundedEvery() { - return interestCompoundedEvery; - } - - public Integer getInterestCompoundedEveryPeriodType() { - return interestCompoundedEveryPeriodType; - } - - public boolean isRenewalAllowed() { - return renewalAllowed; - } - - public boolean isPreClosureAllowed() { - return preClosureAllowed; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public boolean isInterestCompoundingAllowed() { - return interestCompoundingAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public Integer getLockinPeriodType() { - return lockinPeriodType; - } - - public boolean isExternalIdChanged() { - return this.modifiedParameters.contains("externalId"); - } - - public boolean isNameChanged() { - return this.modifiedParameters.contains("name"); - } - - public boolean isDescriptionChanged() { - return this.modifiedParameters.contains("description"); - } - - public boolean isCurrencyCodeChanged() { - return this.modifiedParameters.contains("currencyCode"); - } - - public boolean isDigitsAfterDecimalChanged() { - return this.modifiedParameters.contains("digitsAfterDecimal"); - } - - public boolean isInterestRateChanged() { - return this.modifiedParameters.contains("interestRate"); - } - - public boolean isMinimumBalanceChanged() { - return this.modifiedParameters.contains("minimumBalance"); - } - - public boolean isMaximumBalanceChanged() { - return this.modifiedParameters.contains("maximumBalance"); - } - - public boolean isTenureMonthsChanged() { - return this.modifiedParameters.contains("tenureMonths"); - } - - public boolean isMaturityDefaultInterestRateChanged() { - return this.modifiedParameters.contains("maturityDefaultInterestRate"); - } - - public boolean isMaturityMinInterestRateChanged() { - return this.modifiedParameters.contains("maturityMinInterestRate"); - } - - public boolean isMaturityMaxInterestRateChanged() { - return this.modifiedParameters.contains("maturityMaxInterestRate"); - } - - public boolean isInterestCompoundedEveryChanged() { - return this.modifiedParameters.contains("interestCompoundedEvery"); - } - - public boolean isInterestCompoundedEveryPeriodTypeChanged() { - return this.modifiedParameters.contains("interestCompoundedEveryPeriodType"); - } - - public boolean isRenewalAllowedChanged() { - return this.modifiedParameters.contains("renewalAllowed"); - } - - public boolean isPreClosureAllowedChanged() { - return this.modifiedParameters.contains("preClosureAllowed"); - } - - public boolean isPreClosureInterestRateChanged() { - return this.modifiedParameters.contains("preClosureInterestRate"); - } - - public boolean isNoFieldChanged() { - return this.modifiedParameters.isEmpty(); - } - - public boolean interestCompoundingAllowedChanged() { - return this.modifiedParameters.contains("interestCompoundingAllowed"); - } - - public boolean isLockinPeriodAllowedChanged() { - return this.modifiedParameters.contains("isLockinPeriodAllowed"); - } - - public boolean isLockinPeriodChanged() { - return this.modifiedParameters.contains("lockinPeriod"); - } - - public boolean isLockinPeriodTypeChanged() { - return this.modifiedParameters.contains("lockinPeriodType"); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductData.java deleted file mode 100644 index 672897651..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductData.java +++ /dev/null @@ -1,254 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.data; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.organisation.monetary.data.CurrencyData; - -/** - * Immutable data object representing details of a deposit product. - */ -public class DepositProductData { - - private final Long id; - private final String externalId; - private final String name; - private final String description; - private final String currencyCode; - private final Integer digitsAfterDecimal; - private final BigDecimal minDeposit; - private final BigDecimal maxDeposit; - private final BigDecimal defaultDeposit; - private final Integer tenureInMonths; - private final BigDecimal minInterestRate; - private final BigDecimal maxInterestRate; - private final BigDecimal defaultInterestRate; - private final Integer interestCompoundedEvery; - private final EnumOptionData interestCompoundedEveryPeriodType; - private final CurrencyData currency; - - private final boolean renewalAllowed; - private final boolean preClosureAllowed; - private final BigDecimal preClosureInterestRate; - private final boolean interestCompoundingAllowed; - - private final boolean isLockinPeriodAllowed; - private final Integer lockinPeriod; - private final EnumOptionData lockinPeriodType; - - private final Collection currencyOptions; - private final List interestCompoundedEveryPeriodTypeOptions; - - public DepositProductData(final Long id, final String externalId, - final String name, final String description, final String currencyCode, final Integer digitsAfterDecimal, - final BigDecimal minDeposit, final BigDecimal defaultDeposit, final BigDecimal maxDeposit, final Integer tenureMonths, - final BigDecimal defaultInterestRate, final BigDecimal minInterestRate, - final BigDecimal maxInterestRate, final Integer interestCompoundedEvery, - final EnumOptionData interestCompoundedEveryPeriodType, final boolean renewalAllowed, final boolean preClosureAllowed, - final BigDecimal preClosureInterestRate, final boolean interestCompoundingAllowed, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final EnumOptionData lockinPeriodType,final CurrencyData currencyData) { - - this.id = id; - this.externalId = externalId; - this.name = name; - this.description = description; - this.currencyCode = currencyCode; - this.digitsAfterDecimal = digitsAfterDecimal; - this.minDeposit = minDeposit; - this.defaultDeposit = defaultDeposit; - this.maxDeposit = maxDeposit; - - this.tenureInMonths = tenureMonths; - this.defaultInterestRate = defaultInterestRate; - this.minInterestRate = minInterestRate; - this.maxInterestRate = maxInterestRate; - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType; - this.renewalAllowed = renewalAllowed; - this.preClosureAllowed = preClosureAllowed; - this.preClosureInterestRate = preClosureInterestRate; - this.interestCompoundingAllowed = interestCompoundingAllowed; - - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.currency = currencyData; - this.currencyOptions = null; - this.interestCompoundedEveryPeriodTypeOptions = null; - } - - public DepositProductData(final Collection currencyOptions, - final EnumOptionData defaultInterestCompoundedEveryPeriodType, - final List interestCompoundedEveryPeriodTypeOptions) { - this.id = null; - this.externalId = null; - this.name = null; - this.description = null; - this.currencyCode = null; - this.digitsAfterDecimal = null; - this.minDeposit = null; - this.defaultDeposit = null; - this.maxDeposit = null; - - this.tenureInMonths = null; - this.defaultInterestRate = null; - this.minInterestRate = null; - this.maxInterestRate = null; - this.interestCompoundedEvery = null; - this.interestCompoundedEveryPeriodType = defaultInterestCompoundedEveryPeriodType; - - this.renewalAllowed = false; - this.preClosureAllowed = false; - this.preClosureInterestRate = null; - this.interestCompoundingAllowed = false; - - this.isLockinPeriodAllowed = false; - this.lockinPeriod = null; - this.lockinPeriodType = defaultInterestCompoundedEveryPeriodType; - - this.currency = null; - - this.currencyOptions = currencyOptions; - this.interestCompoundedEveryPeriodTypeOptions = interestCompoundedEveryPeriodTypeOptions; - } - - public DepositProductData(final DepositProductData product, final Collection currencyOptions, - final List interestCompoundedEveryPeriodTypeOptions) { - this.id = product.id; - this.externalId = product.externalId; - this.name = product.name; - this.description = product.description; - this.currencyCode = product.currencyCode; - this.digitsAfterDecimal = product.digitsAfterDecimal; - this.minDeposit = product.minDeposit; - this.defaultDeposit = product.defaultDeposit; - this.maxDeposit = product.maxDeposit; - - this.tenureInMonths = product.tenureInMonths; - this.defaultInterestRate = product.defaultInterestRate; - this.minInterestRate = product.minInterestRate; - this.maxInterestRate = product.maxInterestRate; - this.interestCompoundedEvery = product.interestCompoundedEvery; - this.interestCompoundedEveryPeriodType = product.interestCompoundedEveryPeriodType; - - this.renewalAllowed = product.renewalAllowed; - this.preClosureAllowed = product.preClosureAllowed; - this.preClosureInterestRate = product.preClosureInterestRate; - this.interestCompoundingAllowed = product.interestCompoundingAllowed; - - this.lockinPeriod = product.lockinPeriod; - this.lockinPeriodType = product.lockinPeriodType; - this.isLockinPeriodAllowed = product.isLockinPeriodAllowed; - - this.currencyOptions = currencyOptions; - this.interestCompoundedEveryPeriodTypeOptions = interestCompoundedEveryPeriodTypeOptions; - - if (this.currencyOptions != null && this.currencyOptions.size() == 1) { - this.currency = new ArrayList(this.currencyOptions).get(0); - } else { - this.currency = product.currency; - } - - } - - public Long getId() { - return id; - } - - public String getExternalId() { - return externalId; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public String getCurrencyCode() { - return currencyCode; - } - - public Integer getDigitsAfterDecimal() { - return digitsAfterDecimal; - } - - public BigDecimal getMinimumBalance() { - return minDeposit; - } - - public BigDecimal getMaximumBalance() { - return maxDeposit; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public BigDecimal getMaturityDefaultInterestRate() { - return defaultInterestRate; - } - - public BigDecimal getMaturityMinInterestRate() { - return minInterestRate; - } - - public BigDecimal getMaturityMaxInterestRate() { - return maxInterestRate; - } - - public Integer getInterestCompoundedEvery() { - return interestCompoundedEvery; - } - - public EnumOptionData getInterestCompoundedEveryPeriodType() { - return interestCompoundedEveryPeriodType; - } - - public boolean isRenewalAllowed() { - return renewalAllowed; - } - - public boolean isPreClosureAllowed() { - return preClosureAllowed; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public Collection getCurrencyOptions() { - return currencyOptions; - } - - public List getInterestCompoundedEveryPeriodTypeOptions() { - return interestCompoundedEveryPeriodTypeOptions; - } - - public boolean isInterestCompoundingAllowed() { - return interestCompoundingAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public EnumOptionData getLockinPeriodType() { - return lockinPeriodType; - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductLookup.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductLookup.java deleted file mode 100644 index 608cc28b9..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/data/DepositProductLookup.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.data; - -public class DepositProductLookup { - - private final Long id; - @SuppressWarnings("unused") - private final String name; - - public DepositProductLookup(final Long id, final String name) { - this.id = id; - this.name = name; - } - - public boolean hasId(final Long matchingId) { - return this.id.equals(matchingId); - } - - public Long id() { - return this.id; - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProduct.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProduct.java deleted file mode 100644 index d3d2a49cf..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProduct.java +++ /dev/null @@ -1,450 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.domain; - -import java.math.BigDecimal; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -import org.apache.commons.lang.StringUtils; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsdepositproduct.exception.DepositProductValueOutsideRangeException; -import org.springframework.data.jpa.domain.AbstractPersistable; - -@Entity -@Table(name = "m_product_deposit", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "name_deposit_product"), - @UniqueConstraint(columnNames = { "external_id" }, name = "externalid_deposit_product") }) -public class DepositProduct extends AbstractPersistable { - - @Column(name = "name", nullable = false) - private String name; - - @Column(name = "external_id", length = 100) - private String externalId; - - @Column(name = "description") - private String description; - - @Column(name = "is_deleted", nullable = false) - private boolean deleted = false; - - @Embedded - private MonetaryCurrency currency; - - @Column(name = "min_deposit", scale = 6, precision = 19, nullable = false) - private BigDecimal minDeposit; - - @Column(name = "default_deposit", scale = 6, precision = 19, nullable = false) - private BigDecimal defaultDeposit; - - @Column(name = "max_deposit", scale = 6, precision = 19, nullable = false) - private BigDecimal maxDeposit; - - @Column(name = "interest_compounded_every", nullable = false) - private Integer interestCompoundedEvery; - - @Column(name = "interest_compounded_every_period_enum", nullable = false) - private PeriodFrequencyType interestCompoundedEveryPeriodType; - - @Column(name = "default_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal defaultInterestRate; - - @Column(name = "min_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal minInterestRate; - - @Column(name = "max_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal maxInterestRate; - - @Column(name = "tenure_months", nullable = false) - private Integer tenureInMonths; - - @Column(name = "is_renewal_allowed", nullable = false) - private boolean renewalAllowed = false; - - @Column(name = "is_preclosure_allowed", nullable = false) - private boolean preClosureAllowed = false; - - @Column(name = "is_compounding_interest_allowed", nullable = false) - private boolean interestCompoundingAllowed = false; - - @Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal preClosureInterestRate; - - @Column(name = "is_lock_in_period_allowed", nullable = false) - private boolean isLockinPeriodAllowed = false; - - @Column(name = "lock_in_period", nullable = false) - private Integer lockinPeriod; - - @Column(name = "lock_in_period_type", nullable = false) - private PeriodFrequencyType lockinPeriodType; - - public static DepositProduct assembleFromJson(final JsonCommand command, final PeriodFrequencyType interestCompoundingPeriodType, - final PeriodFrequencyType lockinPeriodType) { - - final String name = command.stringValueOfParameterNamed("name"); - final String externalId = command.stringValueOfParameterNamed("externalId"); - final String description = command.stringValueOfParameterNamed("description"); - final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); - final Integer digitsAfterDecimal = command.integerValueOfParameterNamed("digitsAfterDecimal"); - - final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal); - final BigDecimal minDeposit = command.bigDecimalValueOfParameterNamed("minDeposit"); - final BigDecimal defaultDeposit = command.bigDecimalValueOfParameterNamed("defaultDeposit"); - final BigDecimal maxDeposit = command.bigDecimalValueOfParameterNamed("maxDeposit"); - - final Integer tenureMonths = command.integerValueOfParameterNamed("tenureInMonths"); - final BigDecimal defaultInterestRate = command.bigDecimalValueOfParameterNamed("defaultInterestRate"); - final BigDecimal minInterestRate = command.bigDecimalValueOfParameterNamed("minInterestRate"); - final BigDecimal maxInterestRate = command.bigDecimalValueOfParameterNamed("maxInterestRate"); - final Integer interestCompoundedEvery = command.integerValueOfParameterNamed("interestCompoundedEvery"); - - final boolean canRenew = command.booleanPrimitiveValueOfParameterNamed("canRenew"); - final boolean canPreClose = command.booleanPrimitiveValueOfParameterNamed("canPreClose"); - final BigDecimal preClosureInterestRate = command.bigDecimalValueOfParameterNamed("preClosureInterestRate"); - final boolean isInterestCompoundingAllowed = command.booleanPrimitiveValueOfParameterNamed("isInterestCompoundingAllowed"); - final boolean isLockinPeriodAllowed = command.booleanPrimitiveValueOfParameterNamed("isLockinPeriodAllowed"); - final Integer lockinPeriod = command.integerValueOfParameterNamed("lockinPeriod"); - - return new DepositProduct(name, externalId, description, currency, minDeposit, defaultDeposit, maxDeposit, tenureMonths, - defaultInterestRate, minInterestRate, maxInterestRate, interestCompoundedEvery, - interestCompoundingPeriodType, canRenew, canPreClose, preClosureInterestRate, isInterestCompoundingAllowed, - isLockinPeriodAllowed, lockinPeriod, lockinPeriodType); - } - - protected DepositProduct() { - // - } - - private DepositProduct(final String name, final String externalId, final String description, final MonetaryCurrency currency, - final BigDecimal minDeposit, final BigDecimal defaultDeposit, final BigDecimal maxDeposit, final Integer tenureMonths, - final BigDecimal defaultInterestRate, final BigDecimal minInterestRate, - final BigDecimal maxInterestRate, final Integer interestCompoundedEvery, - final PeriodFrequencyType interestCompoundedEveryPeriodType, final boolean canRenew, final boolean canPreClose, - final BigDecimal preClosureInterestRate, final boolean isInterestCompoundingAllowed, final boolean isLockinPeriodAllowed, - final Integer lockinPeriod, final PeriodFrequencyType lockinPeriodType) { - this.name = name.trim(); - if (StringUtils.isNotBlank(description)) { - this.description = description.trim(); - } else { - this.description = null; - } - if (StringUtils.isNotBlank(externalId)) { - this.externalId = externalId.trim(); - } else { - this.externalId = null; - } - - this.currency = currency; - this.minDeposit = minDeposit; - this.defaultDeposit = defaultDeposit; - this.maxDeposit = maxDeposit; - this.tenureInMonths = tenureMonths; - this.defaultInterestRate = defaultInterestRate; - this.minInterestRate = minInterestRate; - this.maxInterestRate = maxInterestRate; - this.interestCompoundedEvery = interestCompoundedEvery; - this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType; - this.renewalAllowed = canRenew; - this.preClosureAllowed = canPreClose; - this.preClosureInterestRate = preClosureInterestRate; - this.interestCompoundingAllowed = isInterestCompoundingAllowed; - this.isLockinPeriodAllowed = isLockinPeriodAllowed; - this.lockinPeriod = lockinPeriod; - this.lockinPeriodType = lockinPeriodType; - } - - public MonetaryCurrency getCurrency() { - return currency; - } - - public Integer getInterestCompoundedEvery() { - return interestCompoundedEvery; - } - - public PeriodFrequencyType getInterestCompoundedEveryPeriodType() { - return interestCompoundedEveryPeriodType; - } - - public Integer getTenureInMonths() { - return tenureInMonths; - } - - public BigDecimal getDefaultInterestRate() { - return defaultInterestRate; - } - - public BigDecimal getMinInterestRate() { - return minInterestRate; - } - - public BigDecimal getPreClosureInterestRate() { - return preClosureInterestRate; - } - - public boolean isRenewalAllowed() { - return this.renewalAllowed; - } - - public boolean isPreClosureAllowed() { - return this.preClosureAllowed; - } - - public boolean isInterestCompoundingAllowed() { - return interestCompoundingAllowed; - } - - public boolean isLockinPeriodAllowed() { - return isLockinPeriodAllowed; - } - - public Integer getLockinPeriod() { - return lockinPeriod; - } - - public PeriodFrequencyType getLockinPeriodType() { - return lockinPeriodType; - } - - public boolean isDeleted() { - return deleted; - } - - /** - * Delete is a soft delete. Updates flag on product so it wont appear - * in query/report results. - * - * Any fields with unique constraints and prepended with id of record. - */ - public void delete() { - this.deleted = true; - this.name = this.getId() + "_DELETED_" + this.name; - this.externalId = this.getId() + "_DELETED_" + this.externalId; - } - - public Map update(final JsonCommand command) { - - final Map actualChanges = new LinkedHashMap(20); - - final String localeAsInput = command.locale(); - - final String nameParamName = "name"; - if (command.isChangeInStringParameterNamed(nameParamName, this.name)) { - final String newValue = command.stringValueOfParameterNamed(nameParamName); - actualChanges.put(nameParamName, newValue); - this.name = newValue; - } - - final String descriptionParamName = "description"; - if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) { - final String newValue = command.stringValueOfParameterNamed(descriptionParamName); - actualChanges.put(descriptionParamName, newValue); - this.description = newValue; - } - - final String externalIdParamName = "externalId"; - if (command.isChangeInStringParameterNamed(externalIdParamName, this.externalId)) { - final String newValue = command.stringValueOfParameterNamed(externalIdParamName); - actualChanges.put(externalIdParamName, newValue); - this.externalId = newValue; - } - - String currencyCode = this.currency.getCode(); - Integer digitsAfterDecimal = this.currency.getDigitsAfterDecimal(); - - final String digitsAfterDecimalParamName = "digitsAfterDecimal"; - if (command.isChangeInIntegerParameterNamed(digitsAfterDecimalParamName, digitsAfterDecimal)) { - final Integer newValue = command.integerValueOfParameterNamed(digitsAfterDecimalParamName); - actualChanges.put(digitsAfterDecimalParamName, newValue); - actualChanges.put("locale", localeAsInput); - digitsAfterDecimal = newValue; - this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal); - } - - final String currencyCodeParamName = "currencyCode"; - if (command.isChangeInStringParameterNamed(currencyCodeParamName, currencyCode)) { - final String newValue = command.stringValueOfParameterNamed(currencyCodeParamName); - actualChanges.put(currencyCodeParamName, newValue); - currencyCode = newValue; - this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal); - } - - final String minDepositParamName = "minDeposit"; - if (command.isChangeInBigDecimalParameterNamed(minDepositParamName, this.minDeposit)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(minDepositParamName); - actualChanges.put(minDepositParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.minDeposit = newValue; - } - - final String defaultDepositParamName = "defaultDeposit"; - if (command.isChangeInBigDecimalParameterNamed(defaultDepositParamName, this.defaultDeposit)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(defaultDepositParamName); - actualChanges.put(defaultDepositParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.defaultDeposit = newValue; - } - - final String maxDepositParamName = "maxDeposit"; - if (command.isChangeInBigDecimalParameterNamed(maxDepositParamName, this.maxDeposit)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(maxDepositParamName); - actualChanges.put(maxDepositParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.maxDeposit = newValue; - } - - final String tenureInMonthsParamName = "tenureInMonths"; - if (command.isChangeInIntegerParameterNamed(tenureInMonthsParamName, this.tenureInMonths)) { - final Integer newValue = command.integerValueOfParameterNamed(tenureInMonthsParamName); - actualChanges.put(tenureInMonthsParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.tenureInMonths = newValue; - } - - final String defaultInterestRateParamName = "defaultInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(defaultInterestRateParamName, this.defaultInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(defaultInterestRateParamName); - actualChanges.put(defaultInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.defaultInterestRate = newValue; - } - - final String minInterestRateParamName = "minInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(minInterestRateParamName, this.minInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(minInterestRateParamName); - actualChanges.put(minInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.minInterestRate = newValue; - } - - final String maxInterestRateParamName = "maxInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(maxInterestRateParamName, this.maxInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(maxInterestRateParamName); - actualChanges.put(maxInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.maxInterestRate = newValue; - } - - final String interestCompoundedEveryParamName = "interestCompoundedEvery"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryParamName, this.interestCompoundedEvery)) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryParamName); - actualChanges.put(interestCompoundedEveryParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestCompoundedEvery = newValue; - } - - final String interestCompoundedEveryPeriodTypeParamName = "interestCompoundedEveryPeriodType"; - if (command.isChangeInIntegerParameterNamed(interestCompoundedEveryPeriodTypeParamName, - this.interestCompoundedEveryPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(interestCompoundedEveryPeriodTypeParamName); - actualChanges.put(interestCompoundedEveryPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestCompoundedEveryPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - final String renewalAllowedParamName = "renewalAllowed"; - if (command.isChangeInBooleanParameterNamed(renewalAllowedParamName, this.renewalAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(renewalAllowedParamName); - actualChanges.put(renewalAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.renewalAllowed = newValue; - } - - final String preClosureAllowedParamName = "preClosureAllowed"; - if (command.isChangeInBooleanParameterNamed(preClosureAllowedParamName, this.preClosureAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(preClosureAllowedParamName); - actualChanges.put(preClosureAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.preClosureAllowed = newValue; - } - - final String preClosureInterestRateParamName = "preClosureInterestRate"; - if (command.isChangeInBigDecimalParameterNamed(preClosureInterestRateParamName, this.preClosureInterestRate)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(preClosureInterestRateParamName); - actualChanges.put(preClosureInterestRateParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.preClosureInterestRate = newValue; - } - - final String interestCompoundingAllowedParamName = "interestCompoundingAllowed"; - if (command.isChangeInBooleanParameterNamed(interestCompoundingAllowedParamName, this.interestCompoundingAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(interestCompoundingAllowedParamName); - actualChanges.put(interestCompoundingAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.interestCompoundingAllowed = newValue; - } - - final String isLockinPeriodAllowedParamName = "isLockinPeriodAllowed"; - if (command.isChangeInBooleanParameterNamed(isLockinPeriodAllowedParamName, this.isLockinPeriodAllowed)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(isLockinPeriodAllowedParamName); - actualChanges.put(isLockinPeriodAllowedParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.isLockinPeriodAllowed = newValue; - } - - final String lockinPeriodParamName = "lockinPeriod"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodParamName, this.lockinPeriod)) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodParamName); - actualChanges.put(lockinPeriodParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.lockinPeriod = newValue; - } - - final String lockinPeriodTypeParamName = "lockinPeriodType"; - if (command.isChangeInIntegerParameterNamed(lockinPeriodTypeParamName, this.lockinPeriodType.getValue())) { - final Integer newValue = command.integerValueOfParameterNamed(lockinPeriodTypeParamName); - actualChanges.put(lockinPeriodTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.lockinPeriodType = PeriodFrequencyType.fromInt(newValue); - } - - return actualChanges; - } - - public void validateInterestRateInRange(final BigDecimal interestRate) { - boolean inRange = true; - if (interestRate.compareTo(this.minInterestRate) < 0) { - inRange = false; - } - - if (this.maxInterestRate.compareTo(interestRate) < 0) { - inRange = false; - } - - if (!inRange) { - final String actualValue = interestRate.toPlainString(); - final String minValue = (this.minInterestRate == null) ? "" : this.minInterestRate.toPlainString(); - final String maxValue = (this.maxInterestRate == null) ? "" : this.maxInterestRate.toPlainString(); - throw new DepositProductValueOutsideRangeException(actualValue, minValue, maxValue, "deposit.account.maturityInterestRate"); - } - } - - public void validateDepositInRange(final BigDecimal depositAmount) { - boolean inRange = true; - if (depositAmount.compareTo(this.minDeposit) < 0) { - inRange = false; - } - - if (this.maxDeposit != null && this.maxDeposit.compareTo(depositAmount) < 0) { - inRange = false; - } - - if (!inRange) { - final String actualValue = depositAmount.toPlainString(); - final String minValue = (this.minDeposit == null) ? "" : this.minDeposit.toPlainString(); - final String maxValue = (this.maxDeposit == null) ? "" : this.maxDeposit.toPlainString(); - throw new DepositProductValueOutsideRangeException(actualValue, minValue, maxValue, "deposit.account.deposit.amount"); - } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProductRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProductRepository.java deleted file mode 100644 index 407abd8d8..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/DepositProductRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.domain; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -public interface DepositProductRepository extends - JpaRepository, - JpaSpecificationExecutor { - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/TenureTypeEnum.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/TenureTypeEnum.java deleted file mode 100644 index f31e7f890..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/domain/TenureTypeEnum.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.domain; - -public enum TenureTypeEnum { - - INVALID(0, "tenureTypeEnum.invalid"), // - FIXED_PERIOD(1, "tenureTypeEnum.fixedPeriod"), // - PERPETUAL(2, "tenureTypeEnum.perpetual"); - - private final Integer value; - private final String code; - - private TenureTypeEnum(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return value; - } - - public String getCode() { - return code; - } - - public static TenureTypeEnum fromInt(final Integer frequency) { - - TenureTypeEnum tenureTypeEnum = TenureTypeEnum.INVALID; - switch (frequency) { - case 1: - tenureTypeEnum = TenureTypeEnum.FIXED_PERIOD; - break; - case 2: - tenureTypeEnum = TenureTypeEnum.PERPETUAL; - break; - default: - tenureTypeEnum = TenureTypeEnum.INVALID; - break; - } - return tenureTypeEnum; - } - - public boolean isFixedPeriod() { - return this.value.equals(TenureTypeEnum.FIXED_PERIOD.value); - } - - public boolean isPerpetual() { - return this.value.equals(TenureTypeEnum.PERPETUAL.value); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductNotFoundException.java deleted file mode 100644 index a33529e19..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductNotFoundException.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.exception; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - -public class DepositProductNotFoundException extends - AbstractPlatformResourceNotFoundException { - - public DepositProductNotFoundException(Long id) { - super("error.msg.depositproduct.id.invalid", - "Deposit product with identifier " + id + " does not exist", id); - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductValueOutsideRangeException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductValueOutsideRangeException.java deleted file mode 100644 index ee6f2f96a..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/exception/DepositProductValueOutsideRangeException.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.exception; - -import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - -/** - * Exception thrown when an attempt is made update the parent of a root office. - */ -public class DepositProductValueOutsideRangeException extends AbstractPlatformDomainRuleException { - - public DepositProductValueOutsideRangeException(final String actualValue, final String rangeMin, final String rangeMax, - final String fieldCode) { - super("error.msg." + fieldCode + ".outside.of.allowed.range", actualValue + " is outside of allowed range of [" + rangeMin + ", " - + rangeMax + "].", actualValue, rangeMin, rangeMax); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/CreateDepositProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/CreateDepositProductCommandHandler.java deleted file mode 100644 index fc2e9f5c3..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/CreateDepositProductCommandHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositproduct.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositproduct.service.DepositProductWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class CreateDepositProductCommandHandler implements NewCommandSourceHandler { - - private final DepositProductWritePlatformService depositProductWritePlatformService; - - @Autowired - public CreateDepositProductCommandHandler(final DepositProductWritePlatformService depositProductWritePlatformService) { - this.depositProductWritePlatformService = depositProductWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.depositProductWritePlatformService.createDepositProduct(command); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/DeleteDepositProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/DeleteDepositProductCommandHandler.java deleted file mode 100644 index daa3fd519..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/DeleteDepositProductCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositproduct.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositproduct.service.DepositProductWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class DeleteDepositProductCommandHandler implements NewCommandSourceHandler { - - private final DepositProductWritePlatformService depositProductWritePlatformService; - - @Autowired - public DeleteDepositProductCommandHandler(final DepositProductWritePlatformService depositProductWritePlatformService) { - this.depositProductWritePlatformService = depositProductWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositProductWritePlatformService.deleteDepositProduct(command.entityId()); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/UpdateDepositProductCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/UpdateDepositProductCommandHandler.java deleted file mode 100644 index 9a73225f5..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/handler/UpdateDepositProductCommandHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositproduct.handler; - -import org.mifosplatform.commands.handler.NewCommandSourceHandler; -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.portfolio.savingsdepositproduct.service.DepositProductWritePlatformService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UpdateDepositProductCommandHandler implements NewCommandSourceHandler { - -private final DepositProductWritePlatformService depositProductWritePlatformService; - - @Autowired - public UpdateDepositProductCommandHandler(final DepositProductWritePlatformService depositProductWritePlatformService) { - this.depositProductWritePlatformService = depositProductWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - return this.depositProductWritePlatformService.updateDepositProduct(command.entityId(),command); - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/serialization/DepositProductCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/serialization/DepositProductCommandFromApiJsonDeserializer.java deleted file mode 100644 index 94b0a7673..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/serialization/DepositProductCommandFromApiJsonDeserializer.java +++ /dev/null @@ -1,258 +0,0 @@ -package org.mifosplatform.portfolio.savingsdepositproduct.serialization; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.InvalidJsonException; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -@Component -public final class DepositProductCommandFromApiJsonDeserializer { - - /** - * The parameters supported for this command. - */ - private final Set supportedParams = new HashSet(Arrays.asList("locale", "name", "externalId", "description", - "currencyCode", "digitsAfterDecimal", "minDeposit", "defaultDeposit", "maxDeposit", "tenureInMonths", "defaultInterestRate", - "minInterestRate", "maxInterestRate", "interestCompoundedEvery", "interestCompoundedEveryPeriodType", - "renewalAllowed", "preClosureAllowed", "preClosureInterestRate", "interestCompoundingAllowed", "isLockinPeriodAllowed", - "lockinPeriod", "lockinPeriodType")); - - private final FromJsonHelper fromApiJsonHelper; - - @Autowired - public DepositProductCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForCreate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.product"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final String name = fromApiJsonHelper.extractStringNamed("name", element); - baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - - if (fromApiJsonHelper.parameterExists("externalId", element)) { - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100); - } - - if (fromApiJsonHelper.parameterExists("description", element)) { - final String description = fromApiJsonHelper.extractStringNamed("description", element); - baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500); - } - - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); - baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); - - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); - baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); - - final BigDecimal minDeposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minDeposit", element); - baseDataValidator.reset().parameter("minDeposit").value(minDeposit).notNull().zeroOrPositiveAmount(); - - final BigDecimal defaultDeposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("defaultDeposit", element); - baseDataValidator.reset().parameter("defaultDeposit").value(defaultDeposit).notNull().zeroOrPositiveAmount(); - - if (fromApiJsonHelper.parameterExists("maxDeposit", element)) { - final BigDecimal maxDeposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxDeposit", element); - baseDataValidator.reset().parameter("maxDeposit").value(maxDeposit).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("minDeposit").comapareMinimumAndMaximumAmounts(minDeposit, maxDeposit); - baseDataValidator.reset().parameter("defaultDeposit").comapareMinimumAndMaximumAmounts(defaultDeposit, maxDeposit); - baseDataValidator.reset().parameter("minDeposit").comapareMinimumAndMaximumAmounts(minDeposit, defaultDeposit); - } - - final Integer tenureInMonths = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureInMonths").value(tenureInMonths).notNull().zeroOrPositiveAmount(); - - final BigDecimal defaultInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("defaultInterestRate", - element); - baseDataValidator.reset().parameter("defaultInterestRate").value(defaultInterestRate).notNull() - .zeroOrPositiveAmount(); - - final BigDecimal minInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minInterestRate", element); - baseDataValidator.reset().parameter("minInterestRate").value(minInterestRate).notNull().zeroOrPositiveAmount(); - - final BigDecimal maxInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxInterestRate", element); - baseDataValidator.reset().parameter("maxInterestRate").value(maxInterestRate).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("minInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, maxInterestRate); - baseDataValidator.reset().parameter("defaultInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(defaultInterestRate, maxInterestRate); - baseDataValidator.reset().parameter("minInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, defaultInterestRate); - - final Integer interestCompoundedEvery = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEvery", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEvery").value(interestCompoundedEvery).notNull().zeroOrPositiveAmount(); - - final Integer interestCompoundedEveryPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEveryPeriodType", - element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(interestCompoundedEveryPeriodType).notNull() - .inMinMaxRange(1, 3); - - final Boolean renewalAllowed = fromApiJsonHelper.extractBooleanNamed("renewalAllowed", element); - baseDataValidator.reset().parameter("renewalAllowed").value(renewalAllowed) - .trueOrFalseRequired(isBooleanValueUpdated(renewalAllowed)); - - final Boolean preClosureAllowed = fromApiJsonHelper.extractBooleanNamed("preClosureAllowed", element); - baseDataValidator.reset().parameter("preClosureAllowed").value(preClosureAllowed) - .trueOrFalseRequired(isBooleanValueUpdated(preClosureAllowed)); - - final Boolean interestCompoundingAllowed = fromApiJsonHelper.extractBooleanNamed("interestCompoundingAllowed", element); - baseDataValidator.reset().parameter("interestCompoundingAllowed").value(interestCompoundingAllowed) - .trueOrFalseRequired(isBooleanValueUpdated(interestCompoundingAllowed)); - - final BigDecimal preClosureInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("preClosureInterestRate", element); - baseDataValidator.reset().parameter("preClosureInterestRate").value(preClosureInterestRate).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("preClosureInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(preClosureInterestRate, minInterestRate); - - final Boolean isLockinPeriodAllowed = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(isLockinPeriodAllowed) - .trueOrFalseRequired(isBooleanValueUpdated(isLockinPeriodAllowed)); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - public void validateForUpdate(final String json) { - - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams); - - List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.product"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final String name = fromApiJsonHelper.extractStringNamed("name", element); - baseDataValidator.reset().parameter("name").value(name).ignoreIfNull().notBlank().notExceedingLengthOf(100); - - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); - baseDataValidator.reset().parameter("externalId").value(externalId).ignoreIfNull().notExceedingLengthOf(100); - - final String description = fromApiJsonHelper.extractStringNamed("description", element); - baseDataValidator.reset().parameter("description").value(description).ignoreIfNull().notExceedingLengthOf(500); - - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); - baseDataValidator.reset().parameter("currencyCode").value(currencyCode).ignoreIfNull().notBlank(); - - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); - baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).ignoreIfNull().inMinMaxRange(0, 6); - - final BigDecimal minDeposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minDeposit", element); - baseDataValidator.reset().parameter("minDeposit").value(minDeposit).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal defaultDeposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("defaultDeposit", element); - baseDataValidator.reset().parameter("defaultDeposit").value(defaultDeposit).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal maxDeposit = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxDeposit", element); - baseDataValidator.reset().parameter("maxDeposit").value(maxDeposit).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("minDeposit").comapareMinimumAndMaximumAmounts(minDeposit, maxDeposit); - baseDataValidator.reset().parameter("defaultDeposit").comapareMinimumAndMaximumAmounts(defaultDeposit, maxDeposit); - baseDataValidator.reset().parameter("minDeposit").comapareMinimumAndMaximumAmounts(minDeposit, defaultDeposit); - - final Integer tenureInMonths = fromApiJsonHelper.extractIntegerNamed("tenureInMonths", element, Locale.getDefault()); - baseDataValidator.reset().parameter("tenureInMonths").value(tenureInMonths).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal defaultInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("defaultInterestRate", - element); - baseDataValidator.reset().parameter("defaultInterestRate").value(defaultInterestRate).ignoreIfNull() - .zeroOrPositiveAmount(); - - final BigDecimal minInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minInterestRate", element); - baseDataValidator.reset().parameter("minInterestRate").value(minInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - - final BigDecimal maxInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxInterestRate", element); - baseDataValidator.reset().parameter("maxInterestRate").value(maxInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("minInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, maxInterestRate); - baseDataValidator.reset().parameter("defaultInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(defaultInterestRate, maxInterestRate); - baseDataValidator.reset().parameter("minInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(minInterestRate, defaultInterestRate); - - final Integer interestCompoundedEvery = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEvery", element, - Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEvery").value(interestCompoundedEvery).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer interestCompoundedEveryPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCompoundedEveryPeriodType", - element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(interestCompoundedEveryPeriodType).ignoreIfNull() - .inMinMaxRange(1, 3); - - final Boolean renewalAllowed = fromApiJsonHelper.extractBooleanNamed("renewalAllowed", element); - baseDataValidator.reset().parameter("renewalAllowed").value(renewalAllowed).ignoreIfNull() - .trueOrFalseRequired(isBooleanValueUpdated(renewalAllowed)); - - final Boolean preClosureAllowed = fromApiJsonHelper.extractBooleanNamed("preClosureAllowed", element); - baseDataValidator.reset().parameter("preClosureAllowed").value(preClosureAllowed).ignoreIfNull() - .trueOrFalseRequired(isBooleanValueUpdated(preClosureAllowed)); - - final Boolean interestCompoundingAllowed = fromApiJsonHelper.extractBooleanNamed("interestCompoundingAllowed", element); - baseDataValidator.reset().parameter("interestCompoundingAllowed").value(interestCompoundingAllowed).ignoreIfNull() - .trueOrFalseRequired(isBooleanValueUpdated(interestCompoundingAllowed)); - - final BigDecimal preClosureInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("preClosureInterestRate", element); - baseDataValidator.reset().parameter("preClosureInterestRate").value(preClosureInterestRate).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("preClosureInterestRate") - .comapareMinAndMaxOfTwoBigDecmimalNos(preClosureInterestRate, minInterestRate); - - final Boolean lockinPeriodAllowed = fromApiJsonHelper.extractBooleanNamed("isLockinPeriodAllowed", element); - baseDataValidator.reset().parameter("isLockinPeriodAllowed").value(lockinPeriodAllowed).ignoreIfNull() - .trueOrFalseRequired(isBooleanValueUpdated(lockinPeriodAllowed)); - - final Integer lockinPeriod = fromApiJsonHelper.extractIntegerNamed("lockinPeriod", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriod").value(lockinPeriod).ignoreIfNull().zeroOrPositiveAmount(); - - final Integer lockinPeriodType = fromApiJsonHelper.extractIntegerNamed("lockinPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("lockinPeriodType").value(lockinPeriodType).ignoreIfNull().inMinMaxRange(1, 3); - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } - - private Boolean isBooleanValueUpdated(final Boolean actualValue) { - Boolean isUpdated = false; - if (actualValue != null) { - isUpdated = true; - } - return isUpdated; - } - - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } - } - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductCommandValidator.java deleted file mode 100644 index 80e8b458e..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductCommandValidator.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.service; - -import java.util.ArrayList; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.ApiParameterError; -import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; -import org.mifosplatform.portfolio.savingsdepositproduct.command.DepositProductCommand; - -public class DepositProductCommandValidator { - - private final DepositProductCommand command; - - public DepositProductCommandValidator(final DepositProductCommand command) { - this.command=command; - } - - public void validateForCreate() { - - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.product"); - - baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100); - baseDataValidator.reset().parameter("name").value(command.getName()).notBlank(); - baseDataValidator.reset().parameter("description").value(command.getDescription()).notExceedingLengthOf(500); - baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).notBlank(); - baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).notNull().inMinMaxRange(0, 6); - baseDataValidator.reset().parameter("minimumBalance").value(command.getMinimumBalance()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maximumBalance").value(command.getMaximumBalance()).zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("minimumBalance").comapareMinimumAndMaximumAmounts(command.getMinimumBalance(), command.getMaximumBalance()); - - baseDataValidator.reset().parameter("tenureInMonths").value(command.getTenureInMonths()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityDefaultInterestRate").value(command.getMaturityDefaultInterestRate()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityMinInterestRate").value(command.getMaturityMinInterestRate()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityMaxInterestRate").value(command.getMaturityMaxInterestRate()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityMinInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMaturityMinInterestRate(), command.getMaturityMaxInterestRate()); - baseDataValidator.reset().parameter("maturityDefaultInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMaturityDefaultInterestRate(), command.getMaturityMaxInterestRate()); - baseDataValidator.reset().parameter("maturityMinInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getMaturityMinInterestRate(), command.getMaturityDefaultInterestRate()); - - baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()).notNull().inMinMaxRange(1, 3); - - baseDataValidator.reset().parameter("renewalAllowed").trueOrFalseRequired(command.isRenewalAllowedChanged()); - baseDataValidator.reset().parameter("preClosureAllowed").trueOrFalseRequired(command.isPreClosureAllowedChanged()); - baseDataValidator.reset().parameter("interestCompoundingAllowed").trueOrFalseRequired(command.interestCompoundingAllowedChanged()); - - baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).notNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("preClosureInterestRate").comapareMinAndMaxOfTwoBigDecmimalNos(command.getPreClosureInterestRate(), command.getMaturityMinInterestRate()); - - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); - } - } - - public void validateForUpdate() { - - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("deposit.product"); - baseDataValidator.reset().parameter("id").value(command.getId()).notNull(); - baseDataValidator.reset().parameter("externalId").value(command.getExternalId()).ignoreIfNull().notExceedingLengthOf(100); - - baseDataValidator.reset().parameter("name").value(command.getName()).ignoreIfNull().notBlank(); - baseDataValidator.reset().parameter("description").value(command.getDescription()).ignoreIfNull().notExceedingLengthOf(500); - baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).ignoreIfNull().notBlank(); - baseDataValidator.reset().parameter("digitsAfterDecimal").value(command.getDigitsAfterDecimal()).ignoreIfNull().notNull().inMinMaxRange(0, 6); - baseDataValidator.reset().parameter("minimumBalance").value(command.getMinimumBalance()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maximumBalance").value(command.getMaximumBalance()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().comapareMinimumAndMaximumAmounts(command.getMinimumBalance(), command.getMaximumBalance()); - - baseDataValidator.reset().parameter("tenureMonths").value(command.getTenureInMonths()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityDefaultInterestRate").value(command.getMaturityDefaultInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityMinInterestRate").value(command.getMaturityMinInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("maturityMaxInterestRate").value(command.getMaturityMaxInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().comapareMinAndMaxOfTwoBigDecmimalNos(command.getMaturityMinInterestRate(), command.getMaturityMaxInterestRate()); - baseDataValidator.reset().comapareMinAndMaxOfTwoBigDecmimalNos(command.getMaturityDefaultInterestRate(), command.getMaturityMaxInterestRate()); - baseDataValidator.reset().comapareMinAndMaxOfTwoBigDecmimalNos(command.getMaturityMinInterestRate(), command.getMaturityDefaultInterestRate()); - - baseDataValidator.reset().parameter("interestCompoundedEvery").value(command.getInterestCompoundedEvery()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().parameter("interestCompoundedEveryPeriodType").value(command.getInterestCompoundedEveryPeriodType()).ignoreIfNull().inMinMaxRange(1, 3); - baseDataValidator.reset().parameter("preClosureInterestRate").value(command.getPreClosureInterestRate()).ignoreIfNull().zeroOrPositiveAmount(); - baseDataValidator.reset().comapareMinAndMaxOfTwoBigDecmimalNos(command.getPreClosureInterestRate(), command.getMaturityMinInterestRate()); - - if (command.isNoFieldChanged()) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append("deposit.product").append(".no.parameters.for.update"); - StringBuilder defaultEnglishMessage = new StringBuilder("No parameters passed for update."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), "id"); - dataValidationErrors.add(error); - } - - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); - } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformService.java deleted file mode 100644 index 8863abb91..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformService.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.service; - -import java.util.Collection; - -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductData; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductLookup; - -public interface DepositProductReadPlatformService { - - Collection retrieveAllDepositProducts(); - - Collection retrieveAllDepositProductsForLookup(); - - DepositProductData retrieveDepositProductData(Long productId); - - DepositProductData retrieveNewDepositProductDetails(); - -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformServiceImpl.java deleted file mode 100644 index 0c3595542..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductReadPlatformServiceImpl.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.service; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.List; - -import org.mifosplatform.infrastructure.core.data.EnumOptionData; -import org.mifosplatform.infrastructure.core.domain.JdbcSupport; -import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsaccountproduct.service.SavingsDepositEnumerations; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductData; -import org.mifosplatform.portfolio.savingsdepositproduct.data.DepositProductLookup; -import org.mifosplatform.portfolio.savingsdepositproduct.exception.DepositProductNotFoundException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Service; - - - - -@Service -public class DepositProductReadPlatformServiceImpl implements DepositProductReadPlatformService { - - private final PlatformSecurityContext context; - private final JdbcTemplate jdbcTemplate; - - @Autowired - public DepositProductReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) { - this.context = context; - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Override - public Collection retrieveAllDepositProducts() { - this.context.authenticatedUser(); - DepositProductMapper depositProductMapper = new DepositProductMapper(); - String sql = "select " + depositProductMapper.depositProductSchema() + " where dp.is_deleted=0"; - return this.jdbcTemplate.query(sql, depositProductMapper, new Object[] {}); - } - - @Override - public Collection retrieveAllDepositProductsForLookup() { - this.context.authenticatedUser(); - DepositProductLookupMapper depositProductLookupMapper = new DepositProductLookupMapper(); - String sql = "select " + depositProductLookupMapper.depositProductLookupSchema() + " where dp.is_deleted=0"; - return this.jdbcTemplate.query(sql, depositProductLookupMapper, new Object[] {}); - } - - @Override - public DepositProductData retrieveDepositProductData(Long productId) { - try{ - this.context.authenticatedUser(); - DepositProductMapper depositProductMapper = new DepositProductMapper(); - String sql = "select " + depositProductMapper.depositProductSchema() + " where dp.id = ? and dp.is_deleted=0"; - return this.jdbcTemplate.queryForObject(sql, depositProductMapper, new Object[] { productId }); - } catch (EmptyResultDataAccessException e){ - throw new DepositProductNotFoundException(productId); - } - } - - @Override - public DepositProductData retrieveNewDepositProductDetails() { - - List currencyOptions = null; - List interestCompoundedEveryPeriodTypeOptions = null; - EnumOptionData monthly = SavingsDepositEnumerations.interestCompoundingPeriodType(PeriodFrequencyType.MONTHS); - - return new DepositProductData(currencyOptions, monthly, interestCompoundedEveryPeriodTypeOptions); - } - - private static final class DepositProductMapper implements RowMapper { - - public String depositProductSchema() { - return " dp.id as id, dp.external_id as exernalId, dp.name as name, dp.description as description,dp.currency_code as currencyCode, dp.currency_digits as currencyDigits, " - + "dp.min_deposit as minDeposit, dp.default_deposit as defaultDeposit, dp.max_deposit as maxDeposit, dp.tenure_months as tenureMonths, " - + "dp.interest_compounded_every as interestCompoundedEvery, dp.interest_compounded_every_period_enum as interestCompoundedEveryPeriodType, " - + "dp.default_interest_rate as defaultInterestRate, dp.is_compounding_interest_allowed as interestCompoundingAllowed, " - + "dp.min_interest_rate as minInterestRate, dp.max_interest_rate as maxInterestRate, " - + "dp.is_renewal_allowed as canRenew, dp.is_preclosure_allowed as canPreClose, dp.pre_closure_interest_rate as preClosureInterestRate, " - + "dp.is_lock_in_period_allowed as isLockinPeriodAllowed, dp.lock_in_period as lockinPeriod, dp.lock_in_period_type as lockinPeriodType, " - + "curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, curr.display_symbol as currencyDisplaySymbol " - + "from m_product_deposit dp join m_currency curr on curr.code = dp.currency_code "; - } - - @Override - public DepositProductData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - - Long id = rs.getLong("id"); - String exernalId = rs.getString("exernalId"); - String name = rs.getString("name"); - String description = rs.getString("description"); - - String currencyCode = rs.getString("currencyCode"); - Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); - String currencyName = rs.getString("currencyName"); - String currencyNameCode = rs.getString("currencyNameCode"); - String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); - CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol, currencyNameCode); - - BigDecimal minDeposit = rs.getBigDecimal("minDeposit"); - BigDecimal defaultDeposit = rs.getBigDecimal("defaultDeposit"); - BigDecimal maxDeposit = rs.getBigDecimal("maxDeposit"); - - Integer tenureMonths = JdbcSupport.getInteger(rs, "tenureMonths"); - Integer interestCompoundedEvery = JdbcSupport.getInteger(rs, "interestCompoundedEvery"); - Integer interestCompoundedEveryPeriodTypeValue = JdbcSupport.getInteger(rs, "interestCompoundedEveryPeriodType"); - EnumOptionData interestCompoundedEveryPeriodType = SavingsDepositEnumerations - .interestCompoundingPeriodType(interestCompoundedEveryPeriodTypeValue); - - BigDecimal defaultInterestRate = rs.getBigDecimal("defaultInterestRate"); - BigDecimal minInterestRate = rs.getBigDecimal("minInterestRate"); - BigDecimal maxInterestRate = rs.getBigDecimal("maxInterestRate"); - - Boolean canRenew = rs.getBoolean("canRenew"); - Boolean canPreClose = rs.getBoolean("canPreClose"); - Boolean interestCompoundingAllowed = rs.getBoolean("interestCompoundingAllowed"); - - BigDecimal preClosureInterestRate = rs.getBigDecimal("preClosureInterestRate"); - - Boolean isLockinPeriodAllowed = rs.getBoolean("isLockinPeriodAllowed"); - Integer lockinPeriod = JdbcSupport.getInteger(rs, "lockinPeriod"); - Integer lockinPeriodTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodType"); - EnumOptionData lockinPeriodType = SavingsDepositEnumerations.interestCompoundingPeriodType(lockinPeriodTypeValue); - - return new DepositProductData(id, exernalId, name, description, currencyCode, currencyDigits, - minDeposit, defaultDeposit, maxDeposit, tenureMonths, defaultInterestRate, minInterestRate, - maxInterestRate, interestCompoundedEvery, interestCompoundedEveryPeriodType, canRenew, canPreClose, - preClosureInterestRate, interestCompoundingAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType, currencyData); - } - - } - - private static final class DepositProductLookupMapper implements RowMapper { - - public String depositProductLookupSchema() { - return "dp.id as id, dp.name as name from m_product_deposit dp"; - } - - @Override - public DepositProductLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - Long id = rs.getLong("id"); - String name = rs.getString("name"); - - return new DepositProductLookup(id, name); - } - - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformService.java deleted file mode 100644 index f42fd6081..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformService.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.service; - -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; - -public interface DepositProductWritePlatformService { - - CommandProcessingResult createDepositProduct(JsonCommand command); - - CommandProcessingResult updateDepositProduct(Long productId, JsonCommand command); - - CommandProcessingResult deleteDepositProduct(Long productId); -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformServiceJpaRepositoryImpl.java deleted file mode 100644 index ac519abc2..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savingsdepositproduct/service/DepositProductWritePlatformServiceJpaRepositoryImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -/** - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.mifosplatform.portfolio.savingsdepositproduct.service; - -import java.util.Map; - -import org.mifosplatform.infrastructure.core.api.JsonCommand; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; -import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; -import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; -import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.DepositProduct; -import org.mifosplatform.portfolio.savingsdepositproduct.domain.DepositProductRepository; -import org.mifosplatform.portfolio.savingsdepositproduct.exception.DepositProductNotFoundException; -import org.mifosplatform.portfolio.savingsdepositproduct.serialization.DepositProductCommandFromApiJsonDeserializer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class DepositProductWritePlatformServiceJpaRepositoryImpl implements DepositProductWritePlatformService { - - private final static Logger logger = LoggerFactory.getLogger(DepositProductWritePlatformServiceJpaRepositoryImpl.class); - - private final PlatformSecurityContext context; - private final DepositProductRepository depositProductRepository; - private final DepositProductCommandFromApiJsonDeserializer fromApiJsonDeserializer; - - @Autowired - public DepositProductWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final DepositProductRepository depositProductRepository, - final DepositProductCommandFromApiJsonDeserializer fromApiJsonDeserializer) { - this.context = context; - this.depositProductRepository = depositProductRepository; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; - } - - /* - * Guaranteed to throw an exception no matter what the data integrity issue - * is. - */ - private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - - Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("name_deposit_product")) { - final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException("error.msg.desposit.product.duplicate.name", "Deposit product with name: " + name - + " already exists", "name", name); - } - if (realCause.getMessage().contains("externalid_deposit_product")) { - final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.desposit.product.duplicate.externalId", "Deposit product with externalId " - + externalId + " already exists", "externalId", externalId); - } - - logger.error(dve.getMessage(), dve); - throw new PlatformDataIntegrityException("error.msg.deposit.product.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } - - @Transactional - @Override - public CommandProcessingResult createDepositProduct(final JsonCommand command) { - try { - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForCreate(command.json()); - - //By default months - PeriodFrequencyType interestCompoundingPeriodType =PeriodFrequencyType.MONTHS; - PeriodFrequencyType lockinPeriodType = PeriodFrequencyType.MONTHS; - - final Integer interestCompoundingPeriodTypeIntValue = command.integerValueOfParameterNamed("interestCompoundedEveryPeriodType"); - if (interestCompoundingPeriodTypeIntValue != null) { - interestCompoundingPeriodType = PeriodFrequencyType.fromInt(interestCompoundingPeriodTypeIntValue); - } - - final Integer lockinPeriodTypeIntValue = command.integerValueOfParameterNamed("lockinPeriodType"); - if (lockinPeriodTypeIntValue != null) { - lockinPeriodType = PeriodFrequencyType.fromInt(lockinPeriodTypeIntValue); - } - - DepositProduct product = DepositProduct.assembleFromJson(command, interestCompoundingPeriodType, lockinPeriodType); - - this.depositProductRepository.save(product); - - return new CommandProcessingResultBuilder() // - .withEntityId(product.getId()) // - .build(); - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return CommandProcessingResult.empty(); - } - } - - @Transactional - @Override - public CommandProcessingResult updateDepositProduct(final Long productId, final JsonCommand command) { - try { - - this.context.authenticatedUser(); - - this.fromApiJsonDeserializer.validateForUpdate(command.json()); - - DepositProduct product = this.depositProductRepository.findOne(productId); - if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(productId); } - - final Map changes = product.update(command); - - if (!changes.isEmpty()) { - this.depositProductRepository.saveAndFlush(product); - } - - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(productId) // - .with(changes) // - .build(); - - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return CommandProcessingResult.empty(); - } - } - - @Transactional - @Override - public CommandProcessingResult deleteDepositProduct(final Long productId) { - - this.context.authenticatedUser(); - DepositProduct product = this.depositProductRepository.findOne(productId); - if (product == null || product.isDeleted()) { throw new DepositProductNotFoundException(productId); } - product.delete(); - - this.depositProductRepository.save(product); - - return new CommandProcessingResultBuilder() // - .withEntityId(product.getId()) // - .build(); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java index 6b227171c..d45c16743 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java @@ -364,10 +364,10 @@ public class AppUser extends AbstractPersistable implements PlatformUser { return hasNotPermission; } - public void validateHasReadPermission(final String entityType) { + public void validateHasReadPermission(final String resourceType) { - String authorizationMessage = "User has no authority to view " + entityType.toLowerCase() + "s"; - String matchPermission = "READ_" + entityType.toUpperCase(); + final String authorizationMessage = "User has no authority to view " + resourceType.toLowerCase() + "s"; + final String matchPermission = "READ_" + resourceType.toUpperCase(); if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission))) return;